Laravel 4.2 - 为时间戳添加时间


Laravel 4.2 - Adding time to timestamp

在Laravel 4.2中,当在数据库中创建记录时,使用eloquent,我们可以创建created_at和updated_at时间戳。

我想在我正在使用的表中添加第三列,称为expires,我想将该列的值设置为 created_at + 72 hours

有没有"拉拉维尔"的方法可以做到这一点?访问created_at值?还是我应该以不同的方式处理这个问题?

Laravel的created_at是Carbon的一个实例。使用访问器,我们可以像这样填充$model->expires

public function getExpiresAttribute() {
  $expires = clone $this->created_at;
  $expires->addHours(72);
  return $expires;
}

但是,如果您希望能够针对值进行查询(而不仅仅是计算显示),则需要将其存储在数据库中。要让它自动填充,你可以告诉Laravel这是一个日期列,并使用观察者:

public function getDates(){
  return ['created_at', 'updated_at', 'expires'];
}
public static function boot() {
  parent::boot();
  self::creating(function($model) {
    $model->expires = clone $model->created_at;
    $model->expires->addHours(72);
  }
}