DarkFenix
DarkFenix

Reputation: 746

how to perform a sum with laravel in an eloquent relationship

I have a detail table where there is a relationship with the product table, in the detail table I have a product_id field.

I try to multiply the quantity that appears in the detail table and the price that appears in the product table, used DB ::raw but I get a column error not found.

QueryScope in Detalle Model

 $query->with(['product' => function ($query) {
            $query->select('id', 'name', 'price');
        }])
        ->select('*', DB::raw('SUM(count*products.price) as fullcount'))
        ->groupBy('product_id');

Upvotes: 0

Views: 89

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

Use a JOIN:

$query->select('product_id', DB::raw('SUM(count*products.price) as fullcount'))
    ->join('products', 'details.product_id', '=', 'products.id')
    ->groupBy('product_id');

Upvotes: 1

Related Questions