Ad

How To Use Laravel Scope In A Relationship?

- 1 answer

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?

Ad

Answer

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()
Ad
source: stackoverflow.com
Ad