Laravel Model默认值相对时间now()+ 24h

时间:2016-02-11 21:04:04

标签: php mysql laravel eloquent

我在Laravel有一个模型,我希望将默认值设置为从现在起24小时后的时间。

这就是我目前创建表格的方式。

Schema::create('contact_credits', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('amount')->default(0);
        $table->unsignedInteger('amount_used')->default(0);
        $table->unsignedInteger('company_id');
        $table->foreign('company_id')->references('id')->on('companies');
        $table->dateTime('expires_at');//default value now + 24h
        $table->timestamps();
    });

我尝试了以下内容:

...->default(\DB::raw('DATE_ADD(NOW(), INTERVAL 24 HOUR)'));

但是我在尝试迁移时遇到了错误。 我如何让它工作?

1 个答案:

答案 0 :(得分:3)

显然你只能在MySQL中使用常量值作为默认值,但CURRENT_TIMESTAMP除外。但是,您不能在默认值中执行表达式,因此这对于这种情况无用。

我最终覆盖了我的ContactCredit模型的'create'方法,我在其中添加属性并使用Carbon获取正确的时间戳。因此,对于每个创建的实例,在创建它之前,它设置属性。见下文。

class ContactCredit extends Eloquent
{
    protected $fillable = ['amount', 'expires_at'];
    protected $dates = ['expires_at'];

    public function company()
    {
        return $this->belongsTo('Company');
    }

    public static function create(array $attributes)
    {
        $attributes['expires_at'] = \Carbon\Carbon::now()->addHours(24);
        return parent::create($attributes);
    }    
}