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
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.
Also you can use where on the relation. https://laravel.com/docs/10.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns
If you want to add additional filters in the many to many relationship you can use:
or
Further official info here
In your case: