我在 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)'));
但是我在尝试迁移时总是遇到错误。 我如何让它发挥作用?
最佳答案
显然,除了 CURRENT_TIMESTAMP 之外,您只能在 MySQL 中使用常量值作为默认值。但是,您不能在默认值中执行表达式,因此这对这种情况没有用。
我最终覆盖了我的 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);
}
}
关于php - Laravel 模型默认值相对时间 now() + 24h,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35349973/