使用Laravel从数据库中获取最新和不同的值

问题描述 投票:0回答:1

社区新手,对所有贡献者表示感谢!

现在,我需要一种解决方案来从表中获取最新和不同的值。

我拥有的表称为'transactions',其中具有'id','value','remarks','memberId(FK)','created_at'

ID | amount |  memberId | created_at
 1 |  101   |  00001    | 22-04-2018
 2 |  102   |  00002    | 22-04-2018
 3 |  103   |  00002    | 22-04-2018
 4 |  104   |  00001    | 24-04-2018 (latest)
 5 |  105   |  00002    | 25-04-2018 (latest)
 6 |  106   |  00003    | 25-04-2018 (latest)

我的预期结果是

ID | amount |  memberId | created_at
 4 |  104   |  00001    | 24-04-2018
 5 |  105   |  00002    | 25-04-2018
 6 |  106   |  00003    | 25-04-2018

我的代码

      $transactions = Transaction::select('id', 'memberId', 'amount', DB::raw('max(created_at) as latest_depo'), 'created_at', 'amount')
   ->groupBy('memberId')
   ->orderBy('latest_depo' , 'desc')
   ->paginate(50);

但是我最终没有得到每个成员的最新行。我的猜测与值的分组有关。预先感谢!

php laravel distinct
1个回答
0
投票

怎么样:

$transactions = Transaction::latest()
    ->groupBy('memberId')
    ->distinct('memberId')
    ->select('id','amount','memberId','created_at')
    ->paginate(50);

编辑:我在上述查询中添加了groupBy()。如果groupBy()给您一个错误,请验证您的数据库配置as described here


注意:如果您正在使用Laravel雄辩的关系,则memberId列应命名为member_id

© www.soinside.com 2019 - 2024. All rights reserved.