Reputation: 313
I have three tables as shown in the picture.
I would like to run a query that returns: Total_Parcel_Value, Total_Parcel_Delivery of parcels from all orders where customer = A.
Upvotes: 0
Views: 267
Reputation: 306
Try this here:
// Customer Model
...
public function orders(): HasMany
{
return $this->hasMany(Order::class)
}
// Order model
...
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class)
}
public function parcels(): HasMany
{
return $this->hasMany(Parcel::class)
}
// Parcel Model
...
public function order(): BelongsTo
{
return $this->belongsTo(Order::class)
}
Query:
Parcel::selectRaw('SUM(parcel_value)')
->selectRaw('SUM(delivery_fee)')
->whereHas('order.customer', function(Builder $builder) use ($customerName) {
$builder->where('customers.name', $customerName)
})->first()
Upvotes: 0
Reputation: 3847
Assuming your relationships are correctly setup, you could do this query:
$res = Parcel::query()
->whereHas('order', function($q){
$q->where('customer_id', 12);
})
->selectRaw('SUM(parcel_value) as Total_Parcel_Value, SUM(delivery_fee) as Total_Parcel_Delivery')
->first();
$res->Total_Parcel_Value;
$res->Total_Parcel_Delivery;
Upvotes: 1