Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

php - Laravel rename column loss all data

I am new to Laravel and I create a users table using php artisan migrate command:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('username');
        $table->string('email');
        $table->string('password');
        $table->rememberToken();

    });

After that I just needed to change the username column as first_name then I change the schema as follows:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('first_name');
        $table->string('email');
        $table->string('password');
        $table->rememberToken();
    });

If I run the php artisan migrate command again, it says Nothing to migrate, then I used rollback, and I lose all table data.. How can I edit table structure without affecting my data? I hate Laravel doc

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's start with your schema. Your table name is users. It contains a column named username and you want to change it to first_name without losing existing data. You need to create a new migration for this change.

php artian make:migration rename_columns_to_users_table --table=users

A new migration file will be created in your migrations directory. Open it and change it like this:

Schema::table('users', function ($table) {
    $table->renameColumn('username', 'first_name');
});

Save it and then again run

php artisan migrate

You column name will be renamed immediately without losing your old data. Hope you got it now.

You will find more details here: https://laravel.com/docs/5.3/migrations#renaming-columns


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...