Add foreign Key to Existing Table Laravel 4

淺唱寂寞╮ 提交于 2019-12-11 06:42:17

问题


I can´t added a foreign key to existing table, my first migration is:

public function up() {
    Schema::create('clases_inventario', function($t) {
                $t->increments('id');
                $t->integer('grupos_inventario_id');
                $t->integer('laboratorio_id');
                $t->string('codigo', 4);
                $t->string('descripcion', 64);
                $t->boolean('estado')->default(true);
                $t->timestamps();
            });
}

my second migration is to added the forein key is

public function up() {

        Schema::table('clases_inventario', function($table) {
                    $table->foreign('grupos_inventario_id')->references('id')->on('grupos_inventario');
                });
    }

and i run php artisan migration and output next error

 [Exception]
 SQLSTATE[HY000]: General error: 1005 Can't create table 'bd_e_soft.#sql-818
 _55' (errno: 150) (SQL: alter table `clases_inventario` add constraint clas
 es_inventario_grupos_inventario_id_foreign foreign key (`grupos_inventario_
 id`) references `grupos_inventario` (`id`)) (Bindings: array (
 ))

回答1:


Foreign keys need to be unsigned: http://laravel.com/docs/schema#foreign-keys

Change the key of the remote table to unsigned

public function up() {
Schema::create('clases_inventario', function($t) {
            $t->increments('id');
            $t->integer('grupos_inventario_id')->unsigned();
            $t->integer('laboratorio_id');
            $t->string('codigo', 4);
            $t->string('descripcion', 64);
            $t->boolean('estado')->default(true);
            $t->timestamps();
        });
}


来源:https://stackoverflow.com/questions/20801754/add-foreign-key-to-existing-table-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!