laravel 如何从laravel中的最新日期检索数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48780095/
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 retrieve data from the latest date in laravel?
提问by Sushila Singh
In mySql, I can perform to data of latest date as follows:
在 mySql 中,我可以对最新日期的数据执行如下操作:
select * from tbl where date = 'select max(date) from tbl';
But I don't know how to do this is laravel? How to do it?
但我不知道该怎么做这是laravel?怎么做?
采纳答案by Sohel0415
use orderbBy()
:
使用orderbBy()
:
TblModel::orderBy('date','DESC')->first();
Or
或者
DB::table('tbl')->orderBy('date', 'DESC')->first();
Update:
更新:
TblModel::where('date', TblModel::max('date'))->orderBy('date','desc')->get();
回答by Sapnesh Naik
You can use latest()
:
您可以使用latest()
:
DB::table('tbl')->latest()->first(); // considers created_at field by default.
Or
或者
DB::table('items')->latest('date')->first(); //specify your own column
Under the hood:
引擎盖下:
latest()
will orderBy
with the column you provide in descending
order where the default column will be created_at
.
latest()
将orderBy
与您提供的列一起使用,descending
以便默认列的位置created_at
。
//Illuminate\Database\Query\Builder
public function latest($column = 'created_at')
{
return $this->orderBy($column, 'desc');
}
回答by Dexter Bengil
回答by patriziotomato
This is well documented here:
这在此处有详细记录:
https://laravel.com/docs/5.6/eloquent#retrieving-single-models
https://laravel.com/docs/5.6/eloquent#retrieving-single-models
You may also use the
count
,sum
,max
, and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:
您也可以使用
count
,sum
,max
,等汇总通过查询器提供的方法。这些方法返回适当的标量值而不是完整的模型实例:
Examples:
例子:
$max = DB::table('tbl')::max('date');
$max = App\TblModel::where('active', 1)->max('date');
As described already, you do not necessarily need an Model for this using the DB::table
syntax.
如前所述,您不一定需要使用DB::table
语法的模型。
What you should also may want to consider is the performance aspectof your provided answers here (in case you do not use an index on that column at least)
您还应该考虑的是此处提供的答案的性能方面(如果您至少不在该列上使用索引)