📜 ⬆️ ⬇️

Loading Eloquent links using left join instead of additional requests

If you have ever tried to execute the following code to load data from your Eloquent model and get an error:

MyModel::with('relation')->where('relation.title', '=', $title)->orderBy('relation.field', 'asc') 

Then you probably know that Eloquent downloads related data with a separate query and neither filtering nor sorting by it will work.

In this case, my library will probably help you, which allows you to transfer the load of BelongsTo links from additional queries to the main query with the left join.

How to use it?


After installing the package, you need to add a trait to the description of your model:
')
 class MyModel extends \Eloquent { use \SleepingOwl\WithJoin\WithJoinTrait; } 

And that's all, now you have a couple of new methods:

includes ($ relations)


Use this method instead of Model :: with () so that all BelongsTo connections will be converted into a left join `s (the behavior of loading links of other types will not be changed) .

 StreetImage::includes('street')->where('street.id', '<', 10)->get() 

Instead of two familiar queries, one will be executed (<...> in the query - these are all fields of the related table) :

 select `street`.`<…>` as `__f__street---<…>`, `street_images`.* from `street_images` left join `streets` as `street` on `street`.`id` = `street_images`.`street_id` where `street`.`id` < 10 

references ($ relations)


This method allows you to combine the Eloquent default functionality with the functionality of my library:

 MyModel::with('relation', 'relation2')->references('relation')->... 

In this case, “relation2” will be loaded with an additional query, and “relation” - with the use of left join.

GitHub source code

Source: https://habr.com/ru/post/243301/


All Articles