我已经开始在 Laravel 10 上编写小型个人项目。我遇到的问题如下:
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->foreignUuid('role_id')->nullable()->constrained('roles')->change();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->foreignUuid('role_id')->nullable(false)->constrained('roles')->change();
});
}
但是当我运行 php artisan migrate 时,出现以下错误 - SQLSTATE[42S21]: 列已存在: 1060 重复列名 'role_id' (连接: mysql, SQL: alter table users add role_id char(36) null)。
非常感谢您提供有关如何正确更改该列的任何建议。
您可以尝试以下方法:
Schema::table('users', function (Blueprint $table) {
$table->char('role_id', 36)->nullable()->constrained('roles')->change();
});
或者可能使用原始 sql 语句,例如:
DB::statement('ALTER TABLE users MODIFY role_id CHAR(36) NULL');
DB::statement('ALTER TABLE users ADD CONSTRAINT fk_users_role_id FOREIGN KEY (role_id) REFERENCES roles (id)');