猿问

Laravel:在查询数据库时或查询后过滤?

我是一名 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放在一个数组中。有没有办法在上面的查询中做到这一点,还是应该在此之后进行单独的迭代来排序?


跃然一笑
浏览 311回答 2
2回答

慕码人2483693

我想你可以使用 havingRawShopUser::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();如果要将结果作为数组返回,可以使用 pluckShopUser::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

由于在 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();
随时随地看视频慕课网APP
我要回答