简体   繁体   English

Laravel 5.2 如何在不丢失数据的情况下更新迁移

[英]Laravel 5.2 how to update migration without losing data

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.我使用的是laravel 5.2,我通常根据项目要求更新我的数据库,所以我想在不丢失数据库记录的情况下进行。 I don't mean how to seed my database.. I mean when my database is live and I want to update it throw laravel migration.我不是说如何为我的数据库做种。我的意思是当我的数据库处于活动状态并且我想更新它时会引发 Laravel 迁移。 I was going throw Laravel Documentation but I found nothing, so I hope to find somebody help me我正要扔Laravel 文档,但我什么也没找到,所以我希望有人能帮助我

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 .假设您有一个表users其中包含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.然后您意识到您还需要向用户表中添加一个名为mobile_no的新列。 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.在那里设置您的列详细信息,使用php artisan migrate运行php artisan migrate ,仅此php artisan migrate You'll have this new column in your users table without losing previously stored data.您将在users表中拥有这个新列,而不会丢失以前存储的数据。

请注意,当您在已有数据的情况下为表添加新列时,您必须为新列设置默认值或使其为可为空类型..否则最终会出错

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.在这种情况下,您必须回滚迁移。

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然后运行 ​​PHP artisan migrate

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

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