2016-11-27 116 views
1

我有一个章节和图片模式,用一个一对多的关系(部分可以有很多图片,图片中只有一个部分)Laravel:由家长塞让孩子

我能够检索所有图片提供段ID:

$section = '1'; 
$records = Picture::where('section_id', $section)->orderBy('position')->get(); 

如果我想通过检索塞节(或名称)图片? 所有这些例子不工作:

$section = 'wedding'; 
$records = Picture::where('sections.slug', $section)->orderBy('position')->get(); // nope 
$records = Picture::where($this->section()->slug, $section)->orderBy('position')->get(); // nope 

我试着在Laravel文档进行搜索,但我没有得到的情况下... 谢谢

回答

2

用于查询的关系,你应该使用whereHas功能。

如果你的关系被命名为section()Picture模型然后将查询应为:

$section = 'wedding'; 

$records = Picture::whereHas('section', function($q) use($section) { 
          $q->where('slug', $section); 
         }) 
         ->orderBy('position') 
         ->get(); 

Docs

+0

哦,我还以为是一点点“立竿见影” ...谢谢不过,这工作! – Ivan