简体   繁体   English

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

[英]Getting most recent and distinct values from database with Laravel

new to the community, would like to say thankyou to all the contributers!社区新人,想对所有贡献者说声谢谢!

Right now i'm needing a solution to get the Latest & Distinct value from a table.现在我需要一个解决方案来从表中获取最新和不同的值。

The table I have is called ' transactions ' which has 'id', 'value', 'remarks', 'memberId(FK)', 'created_at' .我拥有的表称为 ' 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)

my expected result is我的预期结果是

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

My code我的代码

      $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);

but I end up not getting the Latest Row of each member.但我最终没有得到每个成员的最新行。 My guess is something to do with the grouping of the values.我的猜测与值的分组有关。 Thanks in advance!提前致谢!

How about:怎么样:

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

Edit: I added groupBy() to the above query.编辑:我将groupBy()添加到上述查询中。 If groupBy() gives you an error, verify your database configuration as described here .如果 groupBy() 给您一个错误,请按照此处所述验证您的数据库配置。


Note: If you are using Laravel Eloquent relationships, your memberId column should probably named member_id .注意:如果您使用 Laravel Eloquent 关系,您的memberId列应该命名为member_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM