【发布时间】:2020-02-17 08:54:13
【问题描述】:
我想把这个 Mysql 代码转换成 Laravel Eloquent
select service_id, sum(cnt) from
(
select * from
(
select service_id, count(*) cnt from prdouct_notifs
join products on products.id = prdouct_notifs.product_id
where prdouct_notifs.user_id = 268
and prdouct_notifs.deleted_at is null
and prdouct_notifs.block = 4
group by service_id
) first_table
union All
(
select service_id, count(*) cnt from products
where products.pro_user_id = 268
and products.status = 47575
group by service_id
)
) total_union group by service_id
我将此代码更改为 Laravel Eloquent。
$get_product = Product::where('pro_user_id', 268)
->where('status', 47575)
->groupby('service_id')
->selectRaw('service_id ,count(*) cnt');
$get_final_product = prdouct_notifs::join('products', function ($join){
$join->on('products.id', '=', 'prdouct_notifs.product_id')
->where('prdouct_notifs.user_id', 268)
->where('prdouct_notifs.block', 4);
})
->selectRaw('service_id ,count(*) cnt')
->groupby('service_id')
->unionAll($get_product)
->get();
问题是unionAll之后如何运行groupby
这就是我想改成雄辩的。
total_union group by service_id
【问题讨论】:
-
您真的需要在子查询中按 service_id 分组吗?只要你有所有的结果,你以后肯定可以分组和计数
-
您可以在检索到集合后对其进行分组。 laravel.com/docs/6.x/collections#method-groupby
标签: php mysql laravel laravel-5 eloquent