Laravel 5.2 how to update migration without losing data

前端 未结 4 1612
天涯浪人
天涯浪人 2021-01-30 13:27

I\'m using laravel 5.2 and I usually update my database according to project requirements, so I\'d like to do it without losing database records. I don\'t mean how to seed my da

相关标签:
4条回答
  • 2021-01-30 13:57

    Since you already have data in your tables then instead of rolling back your migrations (which will cause existing data losses) you can create new migration files to update your tables. Suppose you have a table users with columns name, email, password. You stored data in that table. Then you realized that you also do need to add a new column named mobile_no to your users table. To do this you need to create a new migration file. Command will be:

    php artisan make:migration add_mobile_no_columns_to_users_table --table=users
    

    This way a new migration file will be created. Set your column details there, run the migrations using php artisan migrate and that's all. You'll have this new column in your users table without losing previously stored data.

    0 讨论(0)
  • 2021-01-30 13:59

    Please note that when you add a new column for a table while already there are data, you have to set a default value for new column or make it nullable type.. otherwise you will endup with error

    0 讨论(0)
  • 2021-01-30 14:01

    Make a new migration with

    php artisan make:migration change_body_to_nullable_in_reviews_table --table=reviews
    

    where you put this

        public function up()
        {
            Schema::table('reviews', function (Blueprint $table) {
                $table->text('body')->nullable()->change();
            });
        }
    
        public function down()
        {
            Schema::table('reviews', function (Blueprint $table) {
                $table->text('body')->nullable(false)->change();
            });
        }
    

    And then run PHP artisan migrate

    0 讨论(0)
  • 2021-01-30 14:13

    Make sure that when you are adding new column in your table, that column should be nullable, and should not be unique. Otherwise you will face error. Because when a new column is created it will be empty(not unique). In that condition you have to rollback the migration.

    0 讨论(0)
提交回复
热议问题