【问题标题】:Eloquent get top 5 records from each groupEloquent 从每个组中获取前 5 条记录
【发布时间】:2022-11-17 01:43:24
【问题描述】:

我正在尝试使用 Eloquent 查询从每个类别中获取前 5 条记录,类似于如下示例 MySQL 查询;

SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY secid ORDER BY created_at DESC) AS n
    FROM trees
) AS x
WHERE n <= 5

这是我试过的

  $q= Tree::select(['*',DB::raw("ROW_NUMBER() OVER (PARTITION BY secid ORDER BY created_at DESC) AS n")])
         ->WhereRaw(['n','<=','5'])

->选择();

我收到“数组到字符串转换”错误

我试过了

->WhereRaw('n','<=','5')

并得到

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '5 n order by `trees`.`created_at` desc' at line 1

谁能指出我在这里做错了什么? 任何帮助将不胜感激。

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    whereRow方法的第一个参数是一个sql字符串,第二个是一个绑定数组。 为避免此错误,您需要进行以下调用:

    ->whereRaw('n <= ?', [5])
    

    但仍然无法正确构建查询。我建议你使用以下结构:

    $subQuery = DB::table('trees')
        ->selectRaw('*, ROW_NUMBER() OVER (PARTITION BY secid ORDER BY created_at DESC) AS n');
    
    $result = DB::query()->fromSub($subQuery, 'x')
        ->where('n', '<=', 5)->whereRaw()
        ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      相关资源
      最近更新 更多