[英]Laravel whereHas with polymorphic relationship
Laravel 5.8。 我有一只桌cats
:
id | name
---------
1 | jim
2 | mary
和表格colors
:
id | color
----------
1 | white
2 | black
我正在使用多態關系將顏色附加到貓(和其他生物)。 我有一個colorables
表:
id | color_id | colorable_id | colorable_type
---------------------------------------------
1 | 1 | 2 | 'App\Cat'
在我的Cat
模型中,我有
public function colors()
{
return $this->morphToMany('App\Color', 'colorable');
}
我有這個控制器代碼來獲取給定顏色的所有貓:
public function index(Request $request)
{
$cats = new Cat;
if ($request->has('color')) {
$color = $request->color;
$cats->whereHas('colors', function ($query) use ($color) {
$query->where('color_id', $color);
});
}
return $cats->get();
}
但它會返回所有貓,而不管它們的顏色如何。
您將cats 聲明為一個新對象,然后使用條件查詢它。 試試這個
public function index(Request $request)
{
$color = $request->has('color') : $request->get('color') : null;
$cats = Cat::when($color, function ($query) use ($color) {
$query->where('color_id', $color);
})->get();
}
您還可以使用 laravel when() 方法使您的代碼更具可讀性,您的代碼應該如下所示。
public function index(Request $request)
{
$cats = Cat::query();
$query->when($request->has('color'), function ($q) {
return $q->whereHas('colors', function ($query) use ($request->color){
$query->where('color_id', $color);
}
});
return $query->get();
}
將new Cat
更改為Cat::query()
:
public function index(Request $request)
{
$cats = Cat::query();
if ($request->has('color')) {
$color = $request->color;
$cats->whereHas('colors', function ($query) use ($color) {
$query->where('color_id', $color);
});
}
return $cats->get();
}
或者仍然使用new
,但在查詢時分配給變量:
public function index(Request $request)
{
$cats = new Cat;
if ($request->has('color')) {
$color = $request->color;
$cats = $cats->whereHas('colors', function ($query) use ($color) {
$query->where('color_id', $color);
});
}
return $cats->get();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.