Querying on related models using Laravel 4 and Eloquent

本小妞迷上赌 提交于 2019-12-06 04:00:34

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);

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.

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