$suppliers = Supplier::with(
[
'purcheses' => function ($query) {
$query->with(
[
'payments' => function ($query) {
$query->sum('amount');
}
]
)->get();
}
]
)->latest()->get();
I have a suppliers table with has-many relations with purchases of purchases table with has-many relations with payments and payment belongs to purchases, how to get the total sum of payment for each purchase that belongs to this supplier?
CodePudding user response:
I think this package might help you,
The package's readme illustrates various types of relationships that this package supports:
HasMany
ManyToMany
MorphMany
MorphToMany
MorphedByMany
BelongsTo
Here's an example from the readme of a HasMany relationship for a complex relationship:
/*
Country
-> has many
User
-> has many
Post
-> has many
Comment
*/
class Country extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function comments()
{
return $this->hasManyDeep('App\Comment', ['App\User', 'App\Post']);
}
}
// Access country comments
$country->comments();
In the above example, the package uses Eloquent conventions keys, and the package allows you to specify custom keys for local and foreign keys.
CodePudding user response:
You might want to try flatMap and loadSum:
$suppliers = Supplier::with('purchases')
->get();
// Load the payments total for each purchase.
$suppliers
->flatMap
->purchases
->loadSum('payments', 'amount');
return $suppliers;