I am trying to get all relations where a column has a specific value.
I have 3 models:
- Productions
- ProductionPackages
- ProductionProducts
The relationships:
1 Production can have multiple ProductionPackages and 1 ProductionPackages can have multiple ProductionProducts.
My goal: I want a list with all ProductionProducts where the supplier_id equals a id.
The problem: The production model has a status and a date. I only need the products for the productions where date < current_date and status = 1.
This is my current code, it returns the productionProducts but it does not check the where on the production itself, so it also returns the productionProducts where the status = 0.
public function productEntryInput($supplierId){
$supplier = Supplier::find($supplierId);
$productions = ProductionProducts::with(['productionPackage', 'productionPackage.production' => function ($query) use ($supplier) {
$inputDate = Date('Y-m-d');
$query->where('status', 1)->where('packing_plant_id', Session::get('user_packingPlant'))
->whereDate('delivery_date', '<',$inputDate);
}])
->where('supplier_id', $supplier->id)
->get();
dd($productions);
}
What am I doing wrong? The closure in the with is not working.
>Solution :
In your case, you need to use withWhereHas:
public function productEntryInput($supplierId){
$supplier = Supplier::find($supplierId);
$productions = ProductionProducts::with('productionPackage')
->withWhereHas('productionPackage.production', function ($query) use ($supplier) {
$inputDate = Date('Y-m-d');
$query->where('status', 1)
->where('packing_plant_id', Session::get('user_packingPlant'))
->whereDate('delivery_date', '<',$inputDate);
})->where('supplier_id', $supplier->id)
->get();
dd($productions);
}
Let me explain it:
With() method will get productionPackage.production that match the conditions in the closure. The method does nothing with ProductionProducts
WithWhereHas() method will get not only productionPackage.production that matches the conditions in the closure but also ProductionProducts