laravel 在laravel中查找列的最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47914324/
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
Find max value of a column in laravel
提问by Guido Caffa
The problem started because I have a table (Clientes), in which the primary key is not auto-incremental. I want to select the max value stored in a column database.
问题开始是因为我有一个表 (Clientes),其中主键不是自动递增的。我想选择存储在列数据库中的最大值。
Like this select, but with eloquent ORM (Laravel):
像这个选择,但具有雄辩的 ORM (Laravel):
SELECT MAX(Id) FROM Clientes
How can I do this?
我怎样才能做到这一点?
I tried:
我试过:
Cliente::with('id')->max(id);
Cliente::select('id')->max(id);
I prefer not to make a simple raw SELECT MAX(ID) FROM Clientes
我不想做一个简单的原料 SELECT MAX(ID) FROM Clientes
I cannot make it.
我做不到。
Thanks all!
谢谢大家!
回答by Alexey Mezenin
回答by Matthew Mathieson
Laravel makes this very easy, in your case you would use
Laravel 使这很容易,在你的情况下你会使用
$maxValue = Cliente::max('id');
But you can also retrieve the newest record from the table, which will be the highest value as well
但是您也可以从表中检索最新的记录,这也将是最高值
$newestCliente = Cliente::orderBy('id', 'desc')->first(); // gets the whole row
$maxValue = $newestCliente->id;
or for just the value
或者只是为了价值
$maxValue = Cliente::orderBy('id', 'desc')->value('id'); // gets only the id
Or, if you have a created_at
column with the date you could get the value like this
或者,如果您有一created_at
列带有日期的列,您可以获得这样的值
$maxValue = Cliente::latest()->value('id');
Relevant Laravel Documentation: https://laravel.com/docs/5.5/queries#aggregates
相关 Laravel 文档:https://laravel.com/docs/5.5/queries#aggregates
回答by Md Hasan
Cliente::where('column_name', $your_Valu)->max('id') // You get any max column