Laravel迁移将不会添加外键与整数类型(mysql) [英] Laravel migration won't add foreign key with integer type (mysql)

查看:279
本文介绍了Laravel迁移将不会添加外键与整数类型(mysql)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图添加一个前导键,引用参考表中的整数主键。我面临两个问题,laravel尝试创建表的方式,第一是如果我尝试显式输入外键列整数长度为11,以匹配引用列,它认为我想要此列作为主键?我得到错误:

I'm trying to add a foregin key which references an integer primary key in the reference table. I'm facing two issues with the way laravel is trying to create the table the first is that if I try to explicitly enter the foreign key columns integer length of 11 to match the reference column it thinks that I want this column as a primary key? And I get the error:

"Incorrect table definition; there can only be one auto column and it must be defined as a key"

即使我明确地将主键声明为'id'列,下面是我用来产生这个错误的代码:

Even if I explicitly state the primary key as the 'id' column I get this error. Here is the code I am using to produce this error:

    public function up()
{
    Schema::create('ip_bans', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('ip_address', 255);
            $table->integer('ban_id', 11);
            $table->primary('id');
            $table->foreign('ban_id')->references('id')->on('user_bans')->onDelete('set null');
        });
}

这是引用表的模式:

    public function up()
{
    Schema::create('user_bans', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('reason');
            $table->string('banned_user', 16);
            $table->timestamps();
            $table->timestamp('ban_end');
            $table->foreign('banned_user')->references('username')->on('users')->onDelete('cascade');
        });
}

如果我从外键列中删除显式的整数长度11无法创建外键,因为列的长度不匹配,因为列的长度为11,并且'user_bans'表中的引用列为10.有什么我在这里做错了或绕过这个错误吗?

If I remove the explicit integer length of 11 from the foreign key column I am unable to create the foreign key because the columns don't match since the length of the column is 11 and the reference column in 'user_bans' table is 10. Is there anything I am doing wrong here or a way around this error?

推荐答案

您尝试过吗?

$table->integer('ban_id', 11)->unsigned;

Laravel - Foreign Keys (注意此部分下面的粉红色框)

Laravel - Foreign Keys (note the pink box under this section)

这篇关于Laravel迁移将不会添加外键与整数类型(mysql)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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