Querying on related models using Laravel 4 and Eloquent

落花浮王杯 提交于 2019-12-10 10:13:38

问题


Using Laravel 4 I have the following models and relations: Event which hasMany Record which hasMany Item. What I would like to do is something like this

Item::where('events.event_type_id', 2)->paginate(50);

This of cause doesn't work as Eloquent doesn't JOIN the models together when retrieving the records. So how do I go about this without just writing the SQL myself (which I would like to avoid as I want to use pagination).


回答1:


What you want is eager loading.

It works like this if you want to specify additional constraints:

Item::with(array('events' => function($query) {
    return $query->where('event_type_id', 2);
}))->paginate(50);



回答2:


There is a pull request pending here https://github.com/laravel/framework/pull/1951.

This will allow you to use a constraint on the has() method, something like this:

$results = Foo::has(array('bars' => function($query)
{
    $query->where('title', 'LIKE', '%baz%');
}))
->with('bars')
->get();

The idea being you only return Foos that have related Bars that contain the string 'baz' in its title column.

It's also discussed here: https://github.com/laravel/framework/issues/1166. Hopefully it will be merged in soon. Works fine for me when I update my local copy of the Builder class with the updated code in the pull request.



来源:https://stackoverflow.com/questions/16821601/querying-on-related-models-using-laravel-4-and-eloquent

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