迁移时表中的FK无法正常工作

时间:2018-07-02 07:03:46

标签: php laravel laravel-5

那时我为表创建迁移时,通过以下错误出现了问题。

  

Illuminate \ Database \ QueryException:SQLSTATE [HY000]:常规   错误:1005无法创建表SELECT o.input_last_update_timestamp FROM control_staging_scm.control_table o WHERE o.id = 21; SELECT p.id, p.internal_timestamp FROM staging_scm.stg_table1 p WHERE p.internal_timestamp > <result from first query>; yourwebs_veridocedu   (错误号:150“外键约束格式不正确”)(SQL:   更改表#sql-2c46_8e添加约束   user_role_mappings外键(user_role_mappings_user_id_foreign)   在删除级联上引用user_idusers

userrolemapping表的迁移:

id

角色表的迁移:

public function up()
    {
        Schema::create('user_role_mappings', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('user_id');
            $table->integer('group_id');
            $table->integer('roleid');
            $table->integer('status');
            $table->integer('createdby');
            $table->integer('modifiedby');
            $table->string('publicguid');
            $table->string('privateguid');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
        });
    }

用户可迁移:

public function up()
{
    Schema::create('userroles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('rolename');
         $table->integer('status')->default(1);
        $table->integer('createdby')->default(1);
        $table->integer('modifiedby')->default(1);
        $table->string('publicguid');
        $table->string('privateguid');
        $table->timestamps(); 

    });
}

表中的FK无法正常工作,无法进行迁移。

3 个答案:

答案 0 :(得分:1)

increments列是未签名的,您的外键列需要具有相同的签名。因此,您应该像这样更改列:

$table->integer('user_id')->unsigned();
$table->integer('group_id')->unsigned();

答案 1 :(得分:1)

尝试以下方法。

$table->integer('user_id')->unsigned()->index();
$table->integer('group_id')->unsigned()->index();

答案 2 :(得分:0)

两个表都必须使用InnoDB引擎,并且列类型必须匹配:

Schema::create('user_role_mappings', function (Blueprint $table) {
    $table->engine = 'InnoDB';
    $table->unsignedInteger('user_id');
    $table->unsignedInteger('group_id');
});