laravel 如何从laravel中具有相同ID的数据库中获取最新记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36864106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get latest record from the database having same id in laravel?
提问by user3810794
I am trying to to get latest record having the same id. For example I have table
我正在尝试获取具有相同 ID 的最新记录。例如我有桌子
ID | Created_at
1 |2016-04-26
1 |2016-04-20
1 |2016-04-18
2 |2016-04-27
2 |2016-04-19
I want to get result like this
我想得到这样的结果
ID | Created_at
1 |2016-04-26
2 |2016-04-27
How do I do this in Laravel? I was only able to order the record by descending order. Don't know how to pick the latest record of each ID. Thank you.
我如何在 Laravel 中做到这一点?我只能按降序对记录进行排序。不知道如何选择每个ID的最新记录。谢谢你。
回答by Syiwa Wahyu Saputra
Try using Collections service from laravel , and use last()
method. Example:
尝试使用 laravel 的 Collections 服务,并使用last()
方法。例子:
$data = ModelName::all();
$last_data_object = collect($data)->last();
//try to see the object using var_dump()
var_dump($last_data_object);
I get it from https://laravel.com/docs/5.2/collections#method-last
回答by Kreshnik Hasanaj
Try it this way, it will give you the max grouped ID which will be the latest:
试试这种方式,它会给你最大的分组 ID,这将是最新的:
SELECT MAX(ID), Created_at
FROM table
GROUP BY ID, Created_at
回答by krunal nerikar
DB::raw('SELECT * FROM `test` WHERE 1 GROUP BY `ID` ORDER BY `Created_at` ASC');
Try this
尝试这个
回答by user3810794
Thank you everyone for help. I was able to solve this by
谢谢大家的帮助。我能够解决这个问题
DB::raw("SELECT ID,created_at FROM <table name> a WHERE created_at=(SELECT max(created_at) FROM <table name> b WHERE a.ID=b.ID)
回答by fcva
Include the directive Db
包含指令Db
$id = DB::table('your_table')->orderBy('id', 'desc')->value('id');
$id = DB::table('your_table')->orderBy('id', 'desc')->value('id');
If you have user_id.
如果您有 user_id。
$id = DB::table('your_table')->where('user_id', $user_id)->orderBy('id', 'desc')->value('id');
$id = DB::table('your_table')->where('user_id', $user_id)->orderBy('id', 'desc')->value('id');
回答by bipin patel
You can try with whereRaw
to getting last records in groupBy
laravel
您可以尝试whereRaw
在groupBy
Laravel 中获取最后一条记录
$data = Table::whereRaw('Created_at IN (select MAX(Created_at) FROM table GROUP BY ID)')->get();