2016-11-27 117 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