Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 雄辩地以年份格式添加默认值_Mysql_Eloquent_Laravel 5.4 - Fatal编程技术网

Mysql 雄辩地以年份格式添加默认值

Mysql 雄辩地以年份格式添加默认值,mysql,eloquent,laravel-5.4,Mysql,Eloquent,Laravel 5.4,如何在Elounce中使用当前年份作为默认值 Schema::create('year', function(Blueprint $table) { $table->increments('id'); $table->integer('from')->length(4)->default(1950); $table->integer('to')->length(4)->default('YEAR(CURRENT_TIMESTAMP

如何在Elounce中使用当前年份作为默认值

Schema::create('year', function(Blueprint $table) {
    $table->increments('id');
    $table->integer('from')->length(4)->default(1950);
    $table->integer('to')->length(4)->default('YEAR(CURRENT_TIMESTAMP)'); // this is not working
});

即使使用DB::raw'YEARCURRENT\u TIMESTAMP'

我想你也做不到

顺便说一下,您应该使用增量而不是增量,并且不能将4设置为整数的第二个参数


如果您使用Eloquent插入数据,您可以在创建新记录时默认填写当前年份。

您可以使用模型事件解决此问题

将以下代码添加到您的年度模型中:


这一实施奏效了

/app/Providers/AppServiceProvider.php

使用App\Model\Year; 使用App\observer\YearObserver; 类AppServiceProvider扩展了ServiceProvider { 公共函数启动 { 年份::ObserveYearObserver::类; } } /app/observer/YearObserver.php

名称空间应用程序\观察者; 使用App\Model\Year; 班级观察家 { 公共功能创建年份$year { 如果$year->to | |!是_数值$to{ $year->to=日期'Y'; } } }
更清晰的解决方案是将列定义为:

$table->year'to'->默认新表达式'YEARCURDATE'; 在你的应用程序中没有额外的逻辑


这是一个解决办法。但我猜laravel5.4使用Observer来观察创建、创建、删除等事件。一个调整是,如果未提供from&to,则使用日期“Y”,这与mysql默认值更接近
/**
 * Model Events
 */
public static function boot() {

    parent::boot();

    static::creating(function($model)
    {
        $model->to = date('Y');
    }
}