I am trying to create a laravel query builder from the following raw query:
SELECT establishments.*, SUM(invoice_rows.total_price) as total_price_sum
FROM `establishments`
JOIN invoices on invoices.establishment_id = establishments.id
JOIN invoice_rows ON invoice_rows.invoice_id = invoices.id
WHERE invoice_rows.invoice_article_group_id = 11
GROUP BY establishments.id
ORDER BY total_price_sum DESC
I have tried different methods such as: with, whereHas and withCount but I can't seem to create the correct laravel query builder for the raw query.
I think you should take a look at join and Raw in Laravel doc ..
your query should be like this:
$values=DB::table('establishments')->select(['establishments.id',
DB::raw('SUM(invoice_rows.total_price) as total_price_sum')])
->join('invoices','invoices.establishment_id','=','establishments.id')
->join('invoice_rows','invoice_rows.invoice_id','=','invoices.id')
->where('invoice_rows.invoice_article_group_id',11)
->groupBy('establishments.id')
->orderByDesc('total_price_sum')->get();
please note that you cant select establishments.*
and then group by only establishments.id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.