问题
Picked up Laravel recently for an API project and have got it all set up and working, and Ive been migrating an API written from a php function with a concatenated SQL string into Laravel query builder, all is fine apart from one part.
I have a table of stock, and a features table, so I have defined a hasMany
relationship on the model of stock to the features, and when I pass in a string array of features to the query I need to loop over each feature and then get back all the stock items that have those features.
Using a whereIn
is not what I need as that will give me stock that has only one of the features. If I use a standard where
that will give me 0 results as soon as multiple features are added.
I have achieved what I want with the following code, but its terribly slow to execute but I am unsure of a better way to get the same result:
foreach($value as $v){
$builder->whereHas('features', function($query) use ($v) {
$query->where('code', $v);
);
}
回答1:
Use query builder instead of Eloquent to optimize queries... For example:
DB::table('stock')->join('features',function($join){
$join->on('features.id','=','stock.feature_id')
->where('code', $v);
})
->select('') <--- also select columns here..
->get();
Docs: https://laravel.com/docs/5.7/queries
来源:https://stackoverflow.com/questions/53462699/optimising-laravel-query