Laravel 查询模型关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20861871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel querying model relationships
提问by M K
Is there a way to do something similar like this?
有没有办法做类似的事情?
Picture::with('gallery')->where('gallery.path', $galleryPath)->first();
It should search a record, but the query will be applied on its relationship.
它应该搜索记录,但查询将应用于其关系。
回答by Anam
If you are using Laravel 4.1:
如果您使用的是 Laravel 4.1:
$picture = Picture::whereHas('gallery', function($q) use ($galleryPath)
{
$q->where('path', $galleryPath);
})->first();
Laravel 4:
拉维尔4:
$picture = Picture::with(array('gallery' => function($q) use ($galleryPath)
{
$q->where('path', $galleryPath);
}))->first();
回答by Altrim
I believe what you are looking for is Eager Load Contraints
我相信您正在寻找的是Eager Load Contraints
You can specify the condition on your relation using function callback e.g
您可以使用函数回调指定关系的条件,例如
Picture::with(array('gallery' => function($query)
{
$query->where('path', $galleryPath);
}))->get();