如何使用 Laravel Migrations 转换外键中的现有列

Tha*_*tos 6 laravel eloquent laravel-5

I'm having trouble trying to change a column type in laravel to fits it as a compatible column to be a foreign key referencing another table id fields.

I have a a schema like this:

Schema::create('person_organization', function(Blueprint $table){
   ...

   $table->integer('organization_id');
   ...
});
Run Code Online (Sandbox Code Playgroud)

and I want to change the field organization_id to an unsigned type, which will make it able to be a foreign key referencing the id field in the organizations table.

NOTE: Just changing the field type in the creation of the table is not an available option, because the system is running in production mode.

So we need to make a new migration to do these changes.

NOTE 2: i tried the method change as described in laravel docs, but it sticks in a query error, as following:

Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') on delete cascade' at line 1 (SQL: alter table person_organization add constraint person_organization_person_id_foreign foreign key (person_id) references persons () on delete cascade)

Sal*_*far 6

Considering you have already installed doctrine/dbal package in your application Now create migration php artisan make:migration your_migration_name and then in migration insert the below code.

    Schema::table('persons', function(Blueprint $table) { 
    $table->integer('organization_id')->unsigned()->index()->change(); 
    $table->foreign('organization_id')->references('id')->on('organizations')- 
  >onDelete('cascade'); 
})
Run Code Online (Sandbox Code Playgroud)

现在运行命令php artisan migrate,现在你已经完成了。快乐编码...