我是一名 JS 开发人员,但试图用一些 Laravel 帮助我的团队。我有他的查询如下:$customers = ShopUser::selectRaw('shop_users.name, shop_users.email, shop_users.unique_id, shop_users.created_at, SUM(orders.total) AS total_spent, MIN(orders.created_at) AS first_purchase, MAX(orders.created_at) AS last_purchase, count(orders.id) AS total_orders')
->leftJoin('orders', 'orders.customer_id', 'shop_users.id')
->groupBy('shop_users.id')
->get();然后我想把花费超过 1,000 美元unique_id的这个查询的用户total放在一个数组中。有没有办法在上面的查询中做到这一点,还是应该在此之后进行单独的迭代来排序?
2 回答
慕码人2483693
TA贡献1860条经验 获得超9个赞
我想你可以使用 havingRaw
ShopUser::selectRaw('shop_users.name, shop_users.email, shop_users.unique_id, shop_users.created_at, SUM(orders.total) AS total_spent, MIN(orders.created_at) AS first_purchase, MAX(orders.created_at) AS last_purchase, count(orders.id) AS total_orders') ->leftJoin('orders', 'orders.customer_id', 'shop_users.id') ->havingRaw('total_spent > ?', [1000]) ->groupBy('shop_users.id') ->get();
如果要将结果作为数组返回,可以使用 pluck
ShopUser::selectRaw('shop_users.name, shop_users.email, shop_users.unique_id, shop_users.created_at, SUM(orders.total) AS total_spent, MIN(orders.created_at) AS first_purchase, MAX(orders.created_at) AS last_purchase, count(orders.id) AS total_orders') ->leftJoin('orders', 'orders.customer_id', 'shop_users.id') ->havingRaw('total_spent > ?', [1000]) ->groupBy('shop_users.id') ->get() ->pluck('unique_id') ->all()
我还没有测试过,但我希望这会有所帮助
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
由于在 Laravel 中有很多方法可以实现这个目标,我更喜欢 Eloquent Query Builder方法而不是Row Queries。
我假设您需要的只是一个总数超过 1,000 的唯一 ID 列表。例如:[233123、434341、35545123]。
因此,您在代码中编写的任何其他选择、分组和过滤器都将被忽略。
&shopUserIds = ShopUser::whereHas('orders', function ($query) { $query->where(DB::row('SUM(total)'), '>', '1000'); }) ->get() ->map->id ->toArray();
- 2 回答
- 0 关注
- 310 浏览
添加回答
举报
0/150
提交
取消