我有一个Message这样的模型:
class Message extends Model
{
protected $primaryKey = 'message_id';
protected $dates = ['created_at', 'updated_at', 'receiver_deleted_at', 'sender_deleted_at', 'sender_read_at', 'receiver_read_at'];
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,有一些日期字段将日期保存为DATETIME(YYYY-MM-DD HH:MM:SS)格式。
但我希望当获取模型实例时,所有日期字段都转换为unix-timestamp格式,然后返回。
我知道可以对每个字段使用这样的访问器:
public function getCreatedAtAttribute()
{
dd(strtotime($this->attributes['created_at']));
return strtotime($this->attributes['created_at']);
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,我必须为每个字段定义一个像上面这样的函数。
但我想要一种更简单的方法来强制模型以 unix-timestamp 格式返回日期字段。
小智 10
protected $casts = [
'created_at' => 'timestamp',
'updated_at' => 'timestamp'
];
Run Code Online (Sandbox Code Playgroud)
在模型中只需添加这些转换即可获取 unix 时间戳
| 归档时间: |
|
| 查看次数: |
6369 次 |
| 最近记录: |