原文连接:learnku.com/laravel/t/3…
讨论请前往专业的 Laravel 开发者论坛:learnku.com/Laravellaravel
默认状况下,Laravel Eloquent
模型默认数据表有 created_at
和 updated_at
两个字段。固然,咱们能够作不少自定义配置,实现不少有趣的功能。下面举例说明。数据库
若是数据表没有这两个字段,保存数据时 Model::create($arrayOfValues); ——会看到 SQL error
。Laravel
在自动填充 created_at / updated_at
的时候,没法找到这两个字段。数组
禁用自动填充时间戳,只须要在 Eloquent Model
添加上一个属性:bash
class Role extends Model
{
public $timestamps = FALSE;
// ... 其余的属性和方法
}
复制代码
假如当前使用的是非 Laravel
类型的数据库,也就是你的时间戳列的命名方式与此不一样该怎么办? 也许,它们分别叫作 create_time 和 update_time。恭喜,你也能够在模型种这么定义:post
class Role extends Model
{
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
复制代码
如下内容引用官网文档 official Laravel documentation:ui
默认状况下,时间戳自动格式为 'Y-m-d H:i:s'
。 若是您须要自定义时间戳格式, 能够在你的模型中设置 $dateFormat
属性。这个属性肯定日期在数据库中的存储格式,以及在序列化成数组或JSON时的格式:this
class Flight extends Model
{
/**
* 日期时间的存储格式
*
* @var string
*/
protected $dateFormat = 'U';
}
复制代码
当在多对多的关联中,时间戳不会自动填充,例如 用户表 users 和 角色表roles的中间表role_user。spa
在这个模型中您能够这样定义关系:code
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
复制代码
而后当你想用户中添加角色时,能够这样使用:orm
$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();
}
复制代码
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();
复制代码
updated_at
的修改不管什么时候,当修改 Eloquent
记录,都将会自动使用当前时间戳来维护 updated_at 字段,这是个很是棒的特性。
可是有时候你却不想这么作,例如:当增长某个值,认为这不是 “整行更新”。
那么,你能够一切如上—— 只需禁用 timestamps
,记住这是临时的:
$user = User::find(1);
$user->profile_views_count = 123;
$user->timestamps = false;
$user->save();
复制代码
与上一个例子刚好相反,也许您须要仅更新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');
}
}
复制代码
Carbon
类最后一个技巧,但更像是一个提醒,由于您应该已经知道它。
默认状况下,created_at和updated_at字段被自动转换为**$dates**, 因此您不须要将他们转换为Carbon
实例,便可以使用Carbon
的方法。
例如:
$user->created_at->addDays(3);
now()->diffInDays($user->updated_at);
复制代码
就这样,快速但但愿有用的提示!
原文连接:learnku.com/laravel/t/3…
讨论请前往专业的 Laravel 开发者论坛:learnku.com/Laravel