Zakaria Mountassir
Zakaria Mountassir

Reputation: 102

how to use laravel Scope in a relationship?

I'm using laravel I have two models

Product

class Product extends Model
{
    public function productcategories(){
      return $this->hasOne('App\Product\Productcategorie','CategoryID','ProductCategoryId');
    }    
}

and Productcategorie

class Productcategorie extends Model
{
  protected $primaryKey = 'CategoryID';

  public function product(){
    return $this->belongsToMany('App\Product\Product','ProductCategoryId','CategoryID');
  }

  public function scopeCp($query,$id){
    return $query->where('categoryparent_id', '=', $id);
  }
}

The Product model has a scope Cpscope

and i have ProductController with function

function productCatgoryPaFilter(Request $request){
  $categories=  Categoryparent::with('categories')->get();
  $id=$request->id;
  return  $product = Product::with('productcategories')->with('productoption.option')->orderBy('created_at','DESC')->get();
}

i want to get all products with categoryparent_id equal to passed parametre in scope how can i do it?

Upvotes: 0

Views: 85

Answers (1)

Abdullah Al Shakib
Abdullah Al Shakib

Reputation: 2044

If you want to filter data in relational model, use whereHas(). Though i have not tested, give it a try

Product::whereHas('productcategories', function ($query) use($id) {
    $query->cp($id);
})
->orderBy('created_at','DESC')->get()

Upvotes: 1

Related Questions