将外键添加到现有表Laravel 4中 [英] Add foreign Key to Existing Table Laravel 4

查看:68
本文介绍了将外键添加到现有表Laravel 4中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法向现有表添加外键,我的第一个迁移是:

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

我的第二个迁移是添加Forein密钥为

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

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

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

推荐答案

外键需要未签名: 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();
        });
}

这篇关于将外键添加到现有表Laravel 4中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆