使用迁移重命名 Laravel 中的列

Mos*_*ade 5 migration laravel

我使用 Laravel 5.6

我想改变author_IDuser_id

我有如下提到的列:

class CreatePostsTable extends Migration{

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->bigInteger('author_ID');
            $table->bigInteger('category_ID')->nullable();
            $table->longText('post_content');
            $table->text('post_title');
            $table->string('post_slug', 200);
            $table->string('post_type', 20);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用以下链接更改我的列名:

如何使用迁移重命名 Laravel 中的列?

然后创建吹迁移:

php artisan make:migration rename_author_id_in_post_table
Run Code Online (Sandbox Code Playgroud)

重命名迁移文件:

class UpdateUsernameInPostTable extends Migration{

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->renameColumn('author_ID', 'user_id');
        });

    }

    public function down()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->renameColumn('user_id', 'author_ID');
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但是使用运行命令:php artisan migrate我有以下错误:

Symfony\Component\Debug\Exception\FatalThrowableError  : 
Class 'RenameAuthorIdInPostTable' not found
Run Code Online (Sandbox Code Playgroud)

Chi*_*tel 11

只需在删除现有迁移以更新名称后尝试此代码,

php artisan make:migration rename_author_id_in_posts_table --table=posts
Run Code Online (Sandbox Code Playgroud)

它将创建一个迁移,然后在创建的迁移中用这个替换 up() 和 down() 函数,

public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->renameColumn('author_ID', 'user_id');
    });
}
Run Code Online (Sandbox Code Playgroud)

和 down() 函数,

public function down()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->renameColumn('user_id', 'author_ID');
    });
}
Run Code Online (Sandbox Code Playgroud)

有关迁移的更多信息,您可以通过此链接Laravel Migrations

我希望这对你有用。如有疑问请评论。

您的迁移问题:

您正在使用Schema::create()表中的更改方法,因为您已经为帖子表创建了迁移,您不需要Schema::create()只使用Schema::table()方法来更新和更改任何字段。

Schema::create('posts', function (Blueprint $table) {
        $table->renameColumn('author_ID', 'user_id');
    });
Run Code Online (Sandbox Code Playgroud)


Ant*_*neB 5

该错误是因为您的类名与 PHP 迁移文件的名称不对应。文件名用于确定它们所包含的类的名称,因此在未重命名另一个类或文件的情况下不要重命名另一个类或文件,这一点很重要。

将您的班级重命名UpdateUsernameInPostTableRenameAuthorIdInPostTable,它应该可以工作。

如果没有,运行composer dumpauto重新加载自动加载文件就一定可以了。