使用子句选项返回Laravel多对多关系

使用子句选项返回Laravel多对多关系,laravel,Laravel,Laravel中有一个代码: $product = Product::where('slug', $slug)->with('types')->with('brand')->firstOrFail(); return $product; 我正在使用类型数组和品牌数组检索数组 类型具有布尔选项“是否处于活动状态” 如何返回具有活动类型的$product 前 试试这个 $product = Product::where('slug', $slug)->with([

Laravel中有一个代码:

$product = Product::where('slug', $slug)->with('types')->with('brand')->firstOrFail();

return $product;
我正在使用类型数组和品牌数组检索数组

类型具有布尔选项“是否处于活动状态”

如何返回具有活动类型的$product

试试这个

$product = Product::where('slug', $slug)->with([
   'types' => function($query){ $query->where('is_active',true); } ,
   'brand'
])
->firstOrFail();
源文档,

尝试一下

$product = Product::where('slug', $slug)->with([
   'types' => function($query){ $query->where('is_active',true); } ,
   'brand'
])
->firstOrFail();

源文档,

如果您只需要活动类型的产品,还可以对其进行筛选:

$product = Product::with([
    'types' => function($query) { $query->where('is_active',true); },
    'brand'
])
->where('slug', $slug)
->whereHas('types' => function($query) { $query->where('is_active',true); },
->firstOrFail();

如果您只需要激活类型的产品,还可以对其进行过滤:

$product = Product::with([
    'types' => function($query) { $query->where('is_active',true); },
    'brand'
])
->where('slug', $slug)
->whereHas('types' => function($query) { $query->where('is_active',true); },
->firstOrFail();