简体   繁体   中英

alter all tables set default value to null

Due to old migrations in our old laravel application, many $table->timestamps(); have default values of 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


How in Laravel could we accomplish this in a migration file?

  • 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?
  • Loop through all the created_at and updated_at columns and set their values to 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.):

$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

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:

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

Source: https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0

MySQL Dates

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. 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:

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

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

$table->nullableTimestamps();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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