简体   繁体   中英

Querying Laravel Eloquent Relationship

I have three tables.

  • Categories
  • Products
  • Brands

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.

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:

Product::where('brand_id', $brandId)
       ->whereHas('categories', function($q) use(categoryId) {
           $q->where('id', $categoryId);
       })
       ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM