[英]Laravel Eloquent hasMany\hasOne limit parents to children with records
使用Laravel Eloquent和hasOne()\\ hasMany()關系,是否可以將“父”表限制為僅在存在“ child \\ foreign”關系的情況下才檢索結果?
FOOS
+----+------------+
| id | etc |
+----+------------+
| 1 | one |
| 2 | two |
| 3 | three |
| 4 | four |
+----+------------+
BARS
+----+-----+--------+
| id | val | foo_id |
+----+-----+--------+
| 11 | 101 | 1 |
| 12 | 102 | 2 |
| 13 | 203 | 3 |
| 14 | 204 | 4 |
+----+-----+--------+
在Foo類(模型)中
public function highBars(){
return $this->hasOne('App\Bar')->where('val','>','200');
}
在控制器中
Foo::with('highBars')->get();
返回所有FOOS,即使某些high_bars
關系為null。 是否可以僅包含關系值不為null的FOOS結果? (foos.id = 3,4)
檢索...
0 => array:3 [▼
"id" => 1
"etc" => "one"
"high_bars" => null
]
1 => array:3 [▼
"id" => 2
"etc" => "two"
"high_bars" => null
]
2 => array:3 [▼
"id" => 3
"etc" => "three"
"high_bars" => array:2 [▼
"id" => 13
"val" =>203
"foo_id" =>3
]
]
3 => array:3 [▼
"id" => 4
"etc" => "four"
"high_bars" => array:2 [▼
"id" => 14
"val" =>204
"foo_id" =>4
]
]
但這就是我想要的
0 => array:3 [▼
"id" => 3
"etc" => "three"
"high_bars" => array:2 [▼
"id" => 13
"val" =>203
"foo_id" =>3
]
]
1 => array:3 [▼
"id" => 4
"etc" => "four"
"high_bars" => array:2 [▼
"id" => 14
"val" =>204
"foo_id" =>4
]
]
引用文檔 。
訪問模型的記錄時,您可能希望根據關系的存在來限制結果。 例如,假設您要檢索所有具有至少一條評論的博客文章。 為此,您可以將關系的名稱傳遞給has方法:
// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();
您還可以指定一個運算符並計數以進一步自定義查詢:
// Retrieve all posts that have three or more comments...
$posts = Post::has('comments', '>=', 3)->get();
嵌套的has語句也可以使用“點”符號構造。 例如,您可以檢索所有具有至少一項評論和投票的帖子:
// Retrieve all posts that have at least one comment with votes...
$posts = Post::has('comments.votes')->get();
如果您需要更多功能,則可以使用whereHas和orWhereHas方法在您的條件查詢中放置“ where”條件。 這些方法使您可以向關系約束中添加自定義約束,例如檢查注釋的內容:
// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();
對於您的特定示例,這可以通過使用以下方法實現:
Foo::has('highBars')->get();
這還不夠。 定義關系時,您只需要告訴Laravel哪些數據與實體相關聯,但這並不會限制數據的獲取方式。
因此,當您在控制器中執行操作時
Foo::with('highBars')->get();
這里的關鍵是這個get
。 您只是將其限制為任何內容,只是說,讓我擁有所有行,並且除此以外,獲取與此模型關聯的數據。 您需要做的是添加一個約束。
Foo::with('highBars')->whereHas('highBars', function ($query) {
$query->where('val', '>', '200');
})->get();
或快捷方式將是
Foo::has('highBars')->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.