【问题标题】:Eloquent: Get all rows where column value(x) exists in more than one row (SQL DB)Eloquent:获取列值(x)存在于多行中的所有行(SQL DB)
【发布时间】:2020-02-01 15:06:52
【问题描述】:

我想在 Laravel 的 Eloquent 中执行以下原始 SQL 查询:

SELECT distinct user_id FROM order_payment WHERE user_id IN (SELECT user_id FROM order_payment where payment_status = 'paid' GROUP BY user_id HAVING COUNT(*) > 1);

这里我使用where in 和user_id 属性,这样在同一个表(order_payment) 中具有payment_status=paid 并按属性user_id 和count > 1 分组的所有行都被选中,然后最后我们选择distinct user_ids 来自给定的一组用户 ID。

此查询的总体目标是获取所需列值(user_id's in this case) > 1...的所有行...

例如:

we have 3 rows > A, B, C
row A has user_id = 1;
row B has user_id = 1;
row C has user_id = 2;

result should have [user_id: 1] as the count becomes greater than 1

上面的原始查询对我有用,但现在我正在编写一个 api,我想知道如何在 Eloquent 中复制它。

请帮忙!

【问题讨论】:

    标签: php eloquent laravel-5.6 eloquent-relationship


    【解决方案1】:

    因此,可以使用groupBy 和havingRaw 方法来完成此查询的雄辩方式

    我们首先选择需要聚合的列

    OrderPayment::select('user_id', \DB::raw('COUNT(user_id) as payment_made))

    然后我们按我们需要的权限进行分组 - groupBy('user_id'),注意我们分组的属性必须在 select 语句中,否则这将不起作用。

    现在是最后一个子句,我们查看是否有多个行具有相同的user_id,我们使用 > havingRaw('COUNT(user_id) > ?', [1])

    现在整个 eloquent 查询看起来像这样

    OrderPayment::select('user_id', \DB::raw('COUNT(user_id) as payment_made))
        ->groupBy('user_id')
        ->havingRaw('COUNT(user_id) > ?', [1])
        ->get();
    

    请注意,在 select 子句中,我们将 DB 原始语句作为字符串传递给查询构建器,因此应该小心 SQL 注入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多