【问题标题】:Select the distinct latest records based on their creation date根据创建日期选择不同的最新记录
【发布时间】:2022-01-28 12:44:17
【问题描述】:

如何从表中选择最新的不同记录,最好使用 eloquent laravel 的查询构建器。

我试过这个查询没有成功。

 Products::where('depart_id', $depart_id)
                ->distinct("serial_number")
                ->latest()
                ->where('serial_number', ""); // get one of the distinct products

【问题讨论】:

  • latest()方法根据created_at列对记录进行排序。
  • 您遇到什么类型的错误?

标签: php sql laravel database eloquent


【解决方案1】:

你可以试试这个:distinct() 会得到不同的'serial_number'

Products::where('depart_id', $depart_id) 
            ->where('serial_number', "")
            ->distinct();

【讨论】:

    【解决方案2】:

    解决方案是使用

     Products::where('depart_id', $depart_id)
                    ->distinct('serial_number')
                    ->orderBy('serial_number', 'desc')
                    ->orderBy('created_at', 'desc')
                    ->where('serial_number', "serial_number");
    

    这确保了 distinct 只返回每个值的唯一最新记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 2018-06-24
      • 2013-10-02
      相关资源
      最近更新 更多