将外键添加到现有表Laravel 4

时间:2013-12-27 13:40:29

标签: laravel laravel-4

我无法在现有表中添加外键,我的第一次迁移是:

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();
            });
}

我的第二次迁移是添加forein密钥

public function up() {

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

然后我运行php artisan migration并输出下一个错误

 [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 个答案:

答案 0 :(得分:5)

外键需要是无符号的: http://laravel.com/docs/schema#foreign-keys

将远程表的密钥更改为无符号

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();
        });
}
相关问题