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
使用Laravel 4我有以下模型和关系:有很多记录的事件。我想做的是这样的事情
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).
当检索记录时,这一原因并不能作为有说服力的模型一起加入模型。因此,我如何在不编写SQL(我希望避免这种情况,因为我希望使用分页)的情况下进行这些操作呢?
2 个解决方案
#1
6
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
0
There is a pull request pending here https://github.com/laravel/framework/pull/1951.
这里有一个拉请求等待https://github.com/laravel/framework/pull/1951。
This will allow you to use a constraint on the has() method, something like this:
这将允许您对has()方法使用约束,如下所示:
$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.
这个想法是你只返回有相关条的Foos,它在标题栏中包含字符串'baz'。
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://github.com/laravel/framework/issues/1166。希望它能很快被合并。当我用在拉请求中的更新代码更新生成器类的本地副本时,对我来说效果很好。
#1
6
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
0
There is a pull request pending here https://github.com/laravel/framework/pull/1951.
这里有一个拉请求等待https://github.com/laravel/framework/pull/1951。
This will allow you to use a constraint on the has() method, something like this:
这将允许您对has()方法使用约束,如下所示:
$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.
这个想法是你只返回有相关条的Foos,它在标题栏中包含字符串'baz'。
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://github.com/laravel/framework/issues/1166。希望它能很快被合并。当我用在拉请求中的更新代码更新生成器类的本地副本时,对我来说效果很好。