数据库中的最新记录基于雄辩的ORM中创建的时间

时间:2017-11-02 06:51:07

标签: sql laravel eloquent

我的桌子大小很大。我使用两个查询我认为这是昂贵的。我需要有效的查询。

示例

id   qt      created_at
---  ----    -----------
1   1        2017-07-28
2   2        2017-07-28
3   3        2017-07-28
4   1        2017-07-29
5   2        2017-07-29
6   3        2017-07-20

我想显示最新的

4   1        2017-07-29
5   2        2017-07-29

我使用两个查询来执行此操作。我认为它效率不高。我想要有效的查询。

我的代码

$last_time = Table::orderBy('created_at','desc')->first()->created_at;
$latest_records = Table::where('created_at','=',$last_time)->get();

1 个答案:

答案 0 :(得分:0)

首先,为Unix Timestamp创建一个created_at列!

请阅读Laravel日期变更器:https://laravel.com/docs/5.1/eloquent-mutators#date-mutators

  

默认情况下,时间戳的格式为' Y-m-d H:i:s'。如果需要自定义时间戳格式,请在模型上设置$ dateFormat属性。此属性确定数据库中日期属性的存储方式,以及将模型序列化为数组或JSON时的格式

此外,您可以覆盖getDateFormat()

protected function getDateFormat()
{
     return 'U';
}

并在迁移文件中使用它:

$table->integer('updated_at');
$table->integer('created_at');

并且,如果您使用软删除:

$table->integer('deleted_at');

https://laravel.com/docs/4.2/eloquent#timestamps

然后你可以获得如下记录:

$record = DB::table('your_table_name')->orderBy('created_at', 'desc')->get(); dd($record);

希望这能帮到你!