问题开始是因为我有一个表(Clientes),其中主键不是自动增量。我想选择存储在列数据库中的最大值。喜欢这个选择,但有雄辩的orm(Laravel):
SELECT MAX(Id) FROM Clientes
我怎么办?
我试过了:
Cliente::with('id')->max(id)
Cliente::select('id')->max(id)
我不想做一个简单的原始“SELECT MAX(ID)FROM Clientes”
我做不到。
谢谢大家!
Laravel让你很容易,在你的情况下你会使用
$maxValue = Cliente::max('id');
但您也可以从表格中检索最新的记录,这也是最高的值
$newestCliente = Cliente::orderBy('id', 'desc')->first(); // gets the whole row
$maxValue = $newestCliente->id;
或只是价值
$maxValue = Cliente::orderBy('id', 'desc')->value('id'); // gets only the id
或者,如果你有一个带有日期的created_at
列,你就可以获得这样的值
$maxValue = Cliente::latest()->value('id');
相关的Laravel文档:https://laravel.com/docs/5.5/queries#aggregates