Laravel使用with()方法将where子句应用于belongsToMany查询



我有一个带有brand_idproducts表,以及一个带有、product_idcategory_idcategory_products表。

我的产品型号:

class Product extends Model
{
public function categories() {
return $this->belongsToMany(Category::class)->withTimestamps();
}
}

我的品牌模型:

class Brand extends Model
{
public function products() {
return $this->hasMany(Product::class)->with(['categories']);
}
}

我的问题是,如何从属于某个类别的Brand实例中获取产品?

$brand = AppBrand::find(1);
/* 
I want to be able to do something in the likes of :
*/
$brand->products_which_are_under_this_category

products()内部删除with(['categories'])方法并编写类似的查询。

$brand->products()->with(['categories' => function ($query) {
$query->where('category_id', CATEGORY_ID);
}])->get();

希望这能有所帮助。

最新更新