[英]Laravel Eloquent Group By Relation Sum()
I have 3 models 我有3个型号
My relations are as follows: 我的关系如下:
Transaction Model: 交易模式:
public function job() {
return $this->belongsTo('App\Job');
}
Job Model: 工作模式:
public function service() {
return $this->belongsTo('App\Service');
}
I'm trying to query my transactions table and sum the total value and group by service. 我正在尝试查询交易表并汇总总值和按服务分组。
My initial thought was to query Transactions: 我最初的想法是查询事务:
Transaction::with('job')->groupBy('job.service_id');
This doesn't work as job.service_id doesn't exist in the transactions table. 这不起作用,因为job.service_id在事务表中不存在。
My other thought was to do a callback on the Transaction query and do the query for every service_id in the jobs table - This seems like this would work but it seems quite a long winded process. 我的另一个想法是对Transaction查询进行回调,并对作业表中的每个service_id进行查询-这似乎可以工作,但过程似乎很漫长。
My goal output: 我的目标输出:
total_value: 100 总计值:100
service_id: 2 service_id:2
I would then query the services table for the service name. 然后,我将在服务表中查询服务名称。
Try this query : 试试这个查询:
Transaction::join('jobs', 'jobs.id', 'transactions.job_id')
->join('services', 'services.id', 'jobs.service_id')
->select('services.id', \DB::raw('sum(transaction.value)')
->groupBy('services.id')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.