如何从 laravel 中的最新日期检索数据?

How to retrieve data from the latest date in laravel?

在mySql中,我可以对最新日期的数据进行如下操作:

select * from tbl where date = 'select max(date) from tbl';

但是我不知道怎么做laravel?怎么做?

您可以使用 latest():

DB::table('tbl')->latest()->first(); // considers created_at field by default.

或者

DB::table('items')->latest('date')->first(); //specify your own column

幕后花絮:

latest()orderBy 与您按 descending 顺序提供的列一起使用,其中默认列为 created_at.

//Illuminate\Database\Query\Builder
public function latest($column = 'created_at')
{
    return $this->orderBy($column, 'desc');
} 

使用orderbBy():

TblModel::orderBy('date','DESC')->first();

DB::table('tbl')->orderBy('date', 'DESC')->first();

更新:

TblModel::where('date', TblModel::max('date'))->orderBy('date','desc')->get();

这在此处有详细记录:

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:

示例:

$max = DB::table('tbl')::max('date');
$max = App\TblModel::where('active', 1)->max('date');

如前所述,您不一定需要使用 DB::table 语法的模型。

您可能还应该考虑的是您在此处提供的答案的 performance aspect(以防您至少不在该列上使用索引)

您也可以在此处使用 Eloquent 进行查询

TableModel::latest()->first(); // returns the latest inserted record

TableModel::oldest()->first(); // returns the first ever inserted record from your table