【问题标题】:How to get the first two data on group by group and sort by one column sequence on laravel如何在laravel上按组获取前两个数据并按一列序列排序
【发布时间】:2018-09-12 06:40:45
【问题描述】:

a16s 表

id p_id u_id trust time
1   1   1      1    1
2   1   2      1    2
3   1   3      0    3
4   1   4      0    4
5   1   5      0    5
6   2   1      0    1
7   2   2      1    2
8   2   5      0    3
9   2   6      0    4
10  3   2      1    1
11  3   5      1    2
12  3   8      1    3

我想得到 信任组上的前两个数据由 p_id 组并依次显示信任组的数据

id  p_id    u_id    trust   time
1   1        1          1   1
2   1        2          1   2
4   1        4          0   4
5   1        5          0   5
7   2        2          1   2
6   2        1          0   1
8   2        5          0   3
10  3        2          1   1
11  3        5          1   2

我试试查询

  $result = DB::table('a16s')
            ->select ('id','p_id','u_id','trust','time'))
            ->orderBy('time', 'desc')
            ->get()
            ->groupBy('p_id')
            ->get()
            ->groupBy('trust','desc')
            ->map(function ($deal) {
              return $deal->take(2);
              });


    echo '<pre>' ;
    print_r($result);

我得到了错误 Symfony\Component\Debug\Exception\FatalThrowableError (E_RECOVERABLE_ERROR) 类型错误:函数 Illuminate\Support\Collection::get() 的参数太少,在第 48 行的 D:\AppServ\www\comefour\app\Http\Controllers\CodoController.php 中传递了 0,预计至少有 1 个

【问题讨论】:

    标签: laravel group-by query-builder laravel-query-builder


    【解决方案1】:

    在你的第一个 ->get() 之后,数据库查询被转换为一个集合。

    collection get 需要一个键作为参数。

    -&gt;get() 放在构建器查询的末尾。

    像这样:

    $result = DB::table('a16s')
            ->select ('id','p_id','u_id','trust','time'))
            ->orderBy('time', 'desc')
            ->groupBy('p_id') // end of query
            ->get() // get the collection
            ->groupBy('trust','desc')
            ->map(function ($deal) {
              return $deal->take(2);
              });
    

    【讨论】:

    • 我收到错误 ~Illuminate \ Database \ QueryException (42000) SQLSTATE[42000]: 语法错误或访问冲突: 1055 SELECT 列表的表达式 #1 不在 GROUP BY 子句中,并且包含非聚合列 ' product.a16s.id' 在功能上不依赖于 GROUP BY 子句中的列;这与 sql_mode=only_full_group_by ... 不兼容
    • 使用 sql_mode=only_full_group_by 您需要将所有选择添加到您的组中或从您的选择中删除它们。
    • 你的意思是 ->select (*) 吗?
    • 这与您最初的问题无关。这里有更多信息,希望对您有所帮助。 dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2016-09-27
    • 2021-06-10
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多