简体   繁体   English

Laravel模型默认值的相对时间now()+ 24h

[英]Laravel Model default value relative time now() + 24h

I have a Model in Laravel where I want to set the default value to the time 24 hours from now. 我在Laravel中有一个模型,我想将默认值设置为从现在起24小时的时间。

This is how I create the table currently. 这就是我当前创建表的方式。

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();
    });

I tried the following: 我尝试了以下方法:

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

But I keep getting errors when trying to migrate. 但是在尝试迁移时,我总是收到错误消息。 How do I get this to work? 我该如何工作?

Apparently you can only use constant values as default values in MySQL with the exception of CURRENT_TIMESTAMP. 显然,除了CURRENT_TIMESTAMP外,您只能在MySQL中使用常量值作为默认值。 Though, you cannot do expressions in a default value, so this is not useful for this case. 但是,您不能使用默认值来表达表达式,因此在这种情况下这没有用。

I ended up overriding the 'create'-method of my ContactCredit Model where I add the attribute and get the correct timestamp with Carbon. 我最终重写了ContactCredit模型的“创建”方法,在其中添加属性并使用Carbon获得正确的时间戳。 So for every instance that get's created, before it get's created it set's the attribute. 因此,对于创建的每个实例,在创建之前,将其设置为属性。 See below. 见下文。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM