![](/img/trans.png)
[英]How to use query result and query again using LIKE statement in Laravel
[英]Laravel Query using with() statement
嘗試在查詢中使用 with 語句時遇到問題,如下所示
thePage::select('field1','field2')
->with('pagePhotos')
此查詢工作正常,但如果我只想獲取 photoLocation="Miami" 的 pagePhotos 該怎么辦。 此 photoLocation 字段不在 Page Model 上,而僅在 pagePhotos 表上。
下面是一個在黑暗中不起作用的刺傷,但它顯示了我試圖理解的邏輯,我希望!
thePage::select('field1','field2')
->with(
'pagePhotos'->where('photoLocation','=','Miami')
)->get();
編輯
除了這里的答案/評論之外,我發現這幫助我獲得了完美的查詢https://stackoverflow.com/a/41436703/7675570
以防萬一有人有類似的情況,它可能會有所幫助。
使用whereHas
:
thePage::select('field1','field2')
->with('pagePhotos')
->whereHas('pagePhotos', function($query) {
$query->where('photoLocation', '=', 'Miami');
})
->get();
編輯:
如果您想在 pagePhotos 字段上有選擇性,而不是
->with('pagePhotos')
將參數作為數組傳遞
->with(['pagePhotos' => function($query) {
$query->select('field1', 'field2');
}])
我認為您應該使用閉包來處理查詢。
thePage::select('field1','field2')->with(array('pagePhotos' => function($query) {
$query->where('photoLocation','=','Miami');
}))->get();
希望能幫到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.