简体   繁体   English

更改所有表,将默认值设置为null

[英]alter all tables set default value to null

Due to old migrations in our old laravel application, many $table->timestamps(); 由于旧的laravel应用程序中的旧版迁移,许多$table->timestamps(); table- $table->timestamps(); have default values of 0000-00-00 00:00:00 . 的默认值是0000-00-00 00:00:00 Due to our new mysql version, which doesn't allow such dates as default value for timestamps, we have to alter all tables to set the default value of the created_at and updated_at column of all tables to NULL 由于我们的新mysql版本不允许使用日期作为时间戳的默认值,因此我们必须更改所有表以将所有表created_atupdated_at列的默认值设置为NULL


How in Laravel could we accomplish this in a migration file? 在Laravel中,我们如何在迁移文件中完成此任务?

  • A way to loop through all tables and check if there is a created_at and updated_at column and set their default values to NULL or set the timestamps to nullable? 一种遍历所有表并检查是否有created_atupdated_at列并将其默认值设置为NULL或将时间戳设置为可为空的方法?
  • Loop through all the created_at and updated_at columns and set their values to NOW() 遍历所有created_atupdated_at列,并将它们的值设置为NOW()

Can anyone assist me with this? 有人可以协助我吗? :-) :-)

Try something like this (Before changing a column, be sure to add the doctrine/dbal dependency to your composer.json file.): 尝试这样的操作(在更改列之前,请确保将doctrine/dbal依赖项添加到composer.json文件中。):

$tables = DB::select('SHOW TABLES'); // returns an array of tables
foreach($tables as $table) {
    Schema::table($table, function ($t) {
        $t->nullableTimestamp('created_at')->change();
        $t->nullableTimestamp('updated_at')->change();
    });
}

You may have a look on this: https://laravel.com/docs/5.3/migrations#modifying-columns 您可以对此进行查看: https : //laravel.com/docs/5.3/migrations#modifying-columns

You can generate new migrations like update_users_table in order to put in the up method the nullableTimestamps method on the $table like this: 您可以生成新的迁移,例如update_users_table ,以便将up方法的nullableTimestamps方法放在$ table上,如下所示:

Schema::table('users', function ($table) {
    $table->nullableTimestamps()->useCurrent()->change();
});

Source: https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0 资料来源: https : //laravel.com/docs/5.3/upgrade#upgrade-5.3.0

MySQL Dates MySQL日期

Starting with MySQL 5.7, 0000-00-00 00:00:00 is no longer considered a valid date, since strict mode is enabled by default. 从MySQL 5.7开始,因为默认情况下启用了严格模式,所以不再将0000-00-00 00:00:00视为有效日期。 All timestamp columns should receive a valid default value when you insert records into your database. 当您将记录插入到数据库中时,所有时间戳列都应收到有效的默认值。 You may use the useCurrent method in your migrations to default the timestamp columns to the current timestamps, or you may make the timestamps nullable to allow null values: 您可以在迁移中使用useCurrent方法将timestamp列默认为当前时间戳,或者可以使timestamps为可空以允许空值:

$table->timestamp('foo')->nullable();

$table->timestamp('foo')->useCurrent();

$table->nullableTimestamps();

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

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