[英]Querying Laravel Eloquent Relationship
I have three tables. 我有三张桌子。
I have a relation on my categories table to the products like so: 我的类别表与以下产品具有关联:
public function products()
{
return $this->belongsToMany('App\Product','product_sub_categories','subcategory_id','product_id');
}
I have a relation on my Products table to the brands like so: 我在“产品”表上与以下品牌有关联:
public function manuf()
{
return $this->belongsTo('App\Brand','brand');
}
I'm querying the categories table to return products of that category by a certain brand. 我正在查询类别表,以按某个品牌返回该类别的产品。
For example. 例如。
I wan to see all products in Cars category with the brand Fiat. 我希望看到菲亚特(Fiat)品牌的汽车类别中的所有产品。
I've tried the following but I feel Im missing something.. 我尝试了以下方法,但我感觉我缺少一些东西。
$search = 'fiat';
$products = $category->products()->where(function($query) use ($search){
$query->brand->name = $search;
})->get();
to return products of that category by a certain brand
通过某个品牌退回该类别的产品
I assume that you know brand ID and category ID and that products and categories have many to many relationship (since you're using belongsToMany
) and product belongs to brand: 我假设您知道品牌ID和类别ID,并且产品和类别具有多对多的关系(因为您使用的是
belongsToMany
),并且产品属于品牌:
Product::where('brand_id', $brandId)
->whereHas('categories', function($q) use(categoryId) {
$q->where('id', $categoryId);
})
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.