Laravel 使用 with() 方法将 where 子句应用于 belongsToMany 查询
Laravel apply where clause to belongsToMany query using with() method
我有一个 products
table 和 brand_id
,还有一个 category_products
table,product_id
和 category_id
.
我的产品型号:
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 = App\Brand::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();
希望对您有所帮助。
我有一个 products
table 和 brand_id
,还有一个 category_products
table,product_id
和 category_id
.
我的产品型号:
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 = App\Brand::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();
希望对您有所帮助。