<p>我已经开始在Laravel 10上编写一个小的个人项目。我遇到的问题如下:</p>
<ol>
<li>我有一个用户表,其中有一个外键UUID - role_id。</li>
<li>我想在该列上添加nullable属性,而不需要删除表。</li>
<li>我创建了一个新的迁移来进行修改。</li>
<li>安装了doctrine/dbal包,以便(理论上)更改列。</li>
<li>我在迁移中的代码如下:</li>
</ol>
<pre class="brush:php;toolbar:false;">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();
        });
    }</pre>
<p>但是当我运行php artisan migrate时,我得到了以下错误 - SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'role_id' (Connection: mysql, SQL: alter table users add role_id char(36) null)。</p>
<p>非常感谢任何关于如何正确修改列的建议。</p>            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
         
        
        
     
您可以尝试以下操作:
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)');