Model Laravel查询模型关系

Model Laravel查询模型关系,model,laravel,relationship,Model,Laravel,Relationship,有没有办法做类似的事情 Picture::with('gallery')->where('gallery.path', $galleryPath)->first(); 它应该搜索一条记录,但查询将应用于它的关系。我相信您要查找的是 您可以使用函数回调指定关系的条件,例如 Picture::with(array('gallery' => function($query) { $query->where('path', $galleryPath); }))-&

有没有办法做类似的事情

Picture::with('gallery')->where('gallery.path', $galleryPath)->first();

它应该搜索一条记录,但查询将应用于它的关系。

我相信您要查找的是

您可以使用函数回调指定关系的条件,例如

Picture::with(array('gallery' => function($query) 
 {
   $query->where('path', $galleryPath); 
 }))->get();

如果您使用的是Laravel 4.1:

$picture = Picture::whereHas('gallery', function($q) use ($galleryPath)
{
    $q->where('path', $galleryPath);

})->first();
拉维4:

$picture = Picture::with(array('gallery' => function($q) use ($galleryPath)
 {
   $q->where('path', $galleryPath); 
 }))->first();

您的查询将返回所有图片记录,并在路径匹配的位置加载并加入库记录。它应该做的是,只加载那些具有与路径匹配的库的图片记录。你看到区别了吗?嗯,如果你使用的是Laravel 4.1,你可以使用
whereHas
方法,该方法应该返回至少有一个具有指定条件的库的图片记录。对我不起作用:(甚至库::has('pictures')->get()返回一个空数组。