0

i have models as

Product       
  id                  
  name                 
  ....
  ....

example:

1 | Product A 
2 | Product b  
3 | Product c

Category       
  id                 
  category           
  .....

example:

1 | Books    
2 | cds
3 | paper

ProductCategory      
  id                          
  product_id                  
  category_id
  ......

example: 
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3

My Models are like :

Product Model

 public function category()
    {
        return $this->hasMany('App\ProductCategory', 'product_id', 'id');
    }

Category Model

public function product_category()
    {
        return $this->belongsTo('App\ProductCategory', 'category_id', 'id');
    }

ProductCategory Model

public function category()
    {
        return $this->belongsTo('App\Category', 'category_id', 'id')->where('status', '=', 1);
    }

My query is write Laravel Eloquent query where the products which category is "cds"

$products = Product::with('category')
        // ->where('category_id', $cid)
        ->inRandomOrder()
        ->paginate(20);

I want the products which are in particulate category. eg: products which are book category.

saiful
  • 129
  • 2
  • 12

1 Answers1

0

You can use the 'whereHas' method of the query builder as follows:

$products = Product::with('category')
    ->whereHas('category', function ($query) use ($cid) {
        return $query->where('id', $cid);
    }
    ->inRandomOrder()
    ->paginate(20);

The first argument to the method is the name of the relation to be used as a filter, and the second is a function that modifies the query that searches for the existence of a related object.