2016-02-11 60 views
2

我在Laravel有一个模型,我想将默认值设置为24小时后的时间。Laravel模型现在默认值相对时间()+ 24h

这是我如何创建表格。

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)')); 

但我不断收到错误试图迁移的时候。 我如何得到这个工作?

回答

3

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

我最终重写了我的ContactCredit模型的'创建'方法,其中添加了属性并使用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); 
    }  
}