[英]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.