Summarize Sum of a calculated field

Hi! I'm trying to show the sum of a calculated attribute. I have a Transaction model which has many Products. The pivot table has the quantity and the unit price for the product. So i have the attribute amount which is calculated and appended to the transaction.
protected function amount(): Attribute
{
return Attribute::make(
get: function () {
return $this?->products->map(
fn ($product) => $product->pivot->quantity * $product->pivot->unit_price
)->sum();
},
);
}
protected function amount(): Attribute
{
return Attribute::make(
get: function () {
return $this?->products->map(
fn ($product) => $product->pivot->quantity * $product->pivot->unit_price
)->sum();
},
);
}
I can display the amount on my table with TextColumn('amount'), but when i try to add the summary i get a error that transactions.amount is not a field in the DB. So my question is how do i make it use the eloquent model instead of a DB query?
2 Replies
CGM
CGM3mo ago
Product::all() or something similar? Also, is your relation named 'pivot'? I don't think that is the normal way to do pivot tables.
charleswilfriedk
The relation is named 'products'. In this case i have others attributes in the pivot table so to access them i have to use the 'pivot'. And the table contains the transactions, for each transactions via the 'products' relation i get the products for the transaction then with map i calculate the amount of the transaction.