我有一个带有brand_id
的products
表,以及一个带有、product_id
和category_id
的category_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();
希望这能有所帮助。