Optimising Laravel query

眉间皱痕 提交于 2021-01-29 08:11:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!