0
votes

I have a model called Purchases that has a many-to-many relationship with Product model. I created a model to manage the table in the many-to-many relationship called PurchasedProduct. This model is related to an other model called Currency.

Purchases table: Id, number, created_at, updated_at.
Product_table: Id, description, created_at, updated_at.
Currency table: Id, code, name, ratio.
Product_Purchase table: Id, purchase_id, product_id, currency_id, quantity, price.

An User can purchase several Products then, he can pay in many Currencies. To manage every transaction, I want to sum the total (quantity * price) by currency. I've tried to do it with an accessor but all I can do is sum the product of quantity * price without consider the currency.

public function getTotalAttribute($value)
{
    $transformers = $this->transformers();
    return $transformers->sum(\DB::raw('quantity * price'));
}`
1
You should start here by writing the exact raw MySQL query which generates the output you want. Then, worry about transforming that to Eloquent/PHP code.Tim Biegeleisen
@TimBiegeleisen sure, I have it but I'm using just laravel to looking for the resultsGolinmarq
Then you should include that query. I think it would help you get an answer here faster.Tim Biegeleisen
Please provide some sample data and the expected result.Jonas Staudenmeir

1 Answers

1
votes

you can use groupBy

public function getTotalAttribute($value)
{
    $transformers = $this->transformers();
    return $transformers->groupBy('currency_id')
    ->selectRaw('sum(quantity * price) as sum, currency_id')
    ->get();
}