skip to Main Content

I have 2 models: Supplier and Product which are connected via SupplierProduct table with additional fields

For a given $supplier I need to load it’s SupplierProducts (with attached products) filtered by where conditions in both SupplierProduct and Product models

Loading everything would look like:

$supplier->load([
   'supplierProducts.product'
]);

Now how can I load with conditions for both SupplierProduct and Product ?

$supplier->load([
    'supplierProducts' => function ($query) use ($supplierProductParam, $productParam) {
        $query->where('field', $supplierProductParam);       
        // can I query supplierProducts.product here?         
     }, // or can I query supplierProducts.product here?
]);

2

Answers


  1. Define them as many to many relations to each other, using belongsToMany using withPivot in the definition. That relation has wherePivot method to conditionate the pivot model.

    return $this->belongsToMany(Role::class)->withPivot('active', 'created_by')
    

    Also you can use where on the relation. https://laravel.com/docs/10.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns

    Suplier::query()->with('products', function (Relation $relation): void {$relation->wherePivot(....);});
    
    Login or Signup to reply.
  2. If you want to add additional filters in the many to many relationship you can use:

    wherePivot('id', 1) 
    

    or

    wherePivotIn('id', [1])
    

    Further official info here

    In your case:

    $supplier->load([
        'supplierProducts' => function ($query) use ($supplierProductParam, $productParam) {
          $query->where('field',$supplierProductParam)->wherePivotIn('fieldonmanytomany',$supplierProductParam);       
          },
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search