[英]Laravel raw sum query to laravel query builder
I am trying to create a laravel query builder from the following raw query:我正在尝试从以下原始查询创建 Laravel 查询构建器:
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.我尝试了不同的方法,例如:with、whereHas 和 withCount,但我似乎无法为原始查询创建正确的 Laravel 查询构建器。
I think you should take a look at join and Raw in Laravel doc ..我认为你应该看看 Laravel 文档中的join和Raw ..
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
请注意,您不能选择
establishments.*
然后仅按establishments.id
id 分组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.