zoukankan      html  css  js  c++  java
  • 分享 8 个 Laravel 模型时间戳使用技巧

    Laravel

    默认情况下,Laravel Eloquent 模型默认数据表有 created_atupdated_at 两个字段。当然,我们可以做很多自定义配置,实现很多有趣的功能。下面举例说明。


    1.禁用时间戳

    如果数据表没有这两个字段,保存数据时 Model::create($arrayOfValues); ——会看到 SQL errorLaravel 在自动填充 created_at / updated_at 的时候,无法找到这两个字段。

    禁用自动填充时间戳,只需要在 Eloquent Model 添加上一个属性:

    class Role extends Model
    {
        public $timestamps = FALSE;
    
        // ... 其他的属性和方法
    }
    

    2. 修改时间戳默认列表

    假如当前使用的是非 Laravel 类型的数据库,也就是你的时间戳列的命名方式与此不同该怎么办? 也许,它们分别叫做 create_timeupdate_time。恭喜,你也可以在模型种这么定义:

    class Role extends Model
    {
        const CREATED_AT = 'create_time';
        const UPDATED_AT = 'update_time'; 
    
    

    3. 修改时间戳日期/时间格式

    以下内容引用官网文档 official Laravel documentation:

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

    class Flight extends Model
    {
        /**
         * 日期时间的存储格式
         *
         * @var string
         */
        protected $dateFormat = 'U';
    }
    

    4. 多对多: 带时间戳的中间表

    当在多对多的关联中,时间戳不会自动填充,例如 用户表  users 和 角色表roles的中间表role_user

    在这个模型中您可以这样定义关系:

    class User extends Model
    {
        public function roles()
        {
            return $this->belongsToMany(Role::class);
        }
    }
    

    然后当你想用户中添加角色时,可以这样使用:

    $roleID = 1;
    $user->roles()->attach($roleID);
    

    默认情况下,这个中间表不包含时间戳。并且Laravel不会尝试自动填充created_at/updated_at

    但是如果你想自动保存时间戳,您需要在迁移文件中添加created_at/updated_at,然后在模型的关联中加上->withTimestamps();

    public function roles()
    {
        return $this->belongsToMany(Role::class)->withTimestamps();
    }
    
    

    5. 使用latest()oldest()进行时间戳排序

    使用时间戳排序有两个 “快捷方法”。

    取而代之:

    User::orderBy('created_at', 'desc')->get();
    

    这么做更快捷:

    User::latest()->get();
    

    默认情况,latest() 使用 created_at 排序。

    与之对应,有一个 oldest() ,将会这么排序 created_at ascending

    User::oldest()->get();
    

    当然,也可以使用指定的其他字段排序。例如,如果想要使用 updated_at,可以这么做:

    $lastUpdatedUser = User::latest('updated_at')->first();
    

    6. 不触发 updated_at的修改

    无论何时,当修改 Eloquent 记录,都将会自动使用当前时间戳来维护 updated_at 字段,这是个非常棒的特性。

    但是有时候你却不想这么做,例如:当增加某个值,认为这不是 “整行更新”。

    那么,你可以一切如上—— 只需禁用 timestamps,记住这是临时的:

    $user = User::find(1);
    $user->profile_views_count = 123;
    $user->timestamps = false;
    $user->save();
    

    7. 仅更新时间戳和关联时间戳

    与上一个例子恰好相反,也许您需要仅更新updated_at字段,而不改变其他列。

    所以,不建议下面这种写法:

    $user->update(['updated_at' => now()]);
    

    您可以使用更快捷的方法:

    $user->touch();
    

    另一种情况,有时候您不仅希望更新当前模型的updated_at,也希望更新上级关系的记录。

    例如,某个comment被更新,那么您希望将post表的updated_at也更新。

    那么,您需要在模型中定义$touches属性:

    class Comment extends Model {
    
        protected $touches = ['post'];
    
        public function post()
        {
            return $this->belongsTo('Post');
        }
    
    }
    

    8. 时间戳字段自动转换Carbon

    最后一个技巧,但更像是一个提醒,因为您应该已经知道它。

    默认情况下,created_atupdated_at字段被自动转换为$dates
    所以您不需要将他们转换为Carbon实例,即可以使用Carbon的方法。

    例如:

    $user->created_at->addDays(3);
    now()->diffInDays($user->updated_at);
    

    就这样,快速但希望有用的提示!

    转自:https://learnku.com/laravel/t/39353

    --欢迎大家来交流反馈。
  • 相关阅读:
    Aurora 数据库支持多达五个跨区域只读副本
    Amazon RDS 的 Oracle 只读副本
    Amazon EC2 密钥对
    DynamoDB 读取请求单位和写入请求单位
    使用 EBS 优化的实例或 10 Gb 网络实例
    启动 LAMP 堆栈 Web 应用程序
    AWS 中的错误重试和指数退避 Error Retries and Exponential Backoff in AWS
    使用 Amazon S3 阻止公有访问
    路由表 Router Table
    使用MySQLAdmin工具查看QPS
  • 原文地址:https://www.cnblogs.com/hhyl/p/13488421.html
Copyright © 2011-2022 走看看