【问题标题】:Distinct in Laravel ORM?在 Laravel ORM 中与众不同?
【发布时间】:2015-09-08 13:58:11
【问题描述】:

我有下表设置(只是为了解释我的问题):

qid | value | created_at
1      1        2014-01-01 00:10
1      2        2014-01-01 00:12
2      231      2014-01-01 00:10
3      hello    2014-01-01 00:10

我想获得一个具有不同 qids 的数组,按 created_at DESC 排序。

所以数组应该看起来像(例如只有值):

 [2, 231, hello]

我是否需要“原始查询,qid 列上具有不同” - 还是 Laravel5 ORM 方法有另一种方法?

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

    您需要通过created_at 订购,然后通过qid 分组。

    Answer::orderBy('created_at', 'desc')->groupBy('qid')->get();
    

    【讨论】:

    • 谢谢!我现在使用: $Answers = Answer::where('task_uuid', $taskuuid)->orderBy('created_at','desc')->groupBy('question_uuid')->get(); - 但我总是得到第一个值,而不是“最新的” - 所以看起来他忽略了 created_at 子句。
    【解决方案2】:

    在这种情况下,您可以在 qid 上添加一个 groupby 来实现该结果。 包括 order by 以确保您获得所需的 qid。

    例如

    ->groupBy('qid')
    

    【讨论】:

    • 谢谢!我现在使用: $Answers = Answer::where('task_uuid', $taskuuid)->orderBy('created_at','desc')->groupBy('question_uuid')->get(); - 但我总是得到第一个值,而不是“最新的” - 所以看起来他忽略了 created_at 子句。
    • 如果这对您不起作用,您可能需要尝试stackoverflow.com/questions/18159465/…
    • 哦,谢谢,我会试试看!看来我需要使用原始查询方法。
    猜你喜欢
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2012-07-02
    • 2020-11-23
    • 2022-12-05
    相关资源
    最近更新 更多