Download Eloquent links using left join instead of additional queries

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

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

    You probably know that Eloquent loads related data in a separate request and neither filtering nor sorting will work on it.

    In this case, my library may help you, which allows you to transfer the loading of BelongsTo links from additional requests to the main request with left join.

    How to use it?

    After installing the package, you need to add the trait to the description of your model:

    class MyModel extends \Eloquent
    	use \SleepingOwl\WithJoin\WithJoinTrait;

    And that's it, now a couple of new methods are available to you:

    includes ($ relations)

    Use this method instead of Model :: with () so that all BelongsTo links are converted to left joins (loading behavior of links of other types will not be changed) .

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

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

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

    references ($ relations)

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

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

    In this case, relation2 will be loaded with an additional request, and relation will be loaded using left join.

    GitHub source code

    Also popular now: