简体   繁体   English

创建复合外键时出现Laravel错误

[英]Laravel Error when creating composite foreign key

I need to build a table named 'slides' that contains two columns named 'id' and 'work_id'. 我需要构建一个名为“幻灯片”的表,其中包含名为“ id”和“ work_id”的两列。 The ID is not an AUTO_INCREMENT integer because I need to keep the numbers as the index inside a slideshow. 该ID不是AUTO_INCREMENT整数,因为我需要将数字保留为幻灯片放映中的索引。

This is the error that is displayed when running 'php artisan migrate': 这是运行“ php artisan migration”时显示的错误: 错误

And this is my code: 这是我的代码:

Schema::create('slides', function(Blueprint $table) {
    $table->integer('id');
    $table->integer('work_id');

    $table->primary(['id', 'work_id']);
    $table->foreign('work_id')->references('id')->on('works');
});

This is the structure of my 'works' table: 这是我的“作品”表的结构: 作品表

And this is the structure of the 'slides' table that is generated despite the error occurring: 这是尽管发生错误但仍生成的“幻灯片”表的结构: 滑台

I don't understand the error message because I'm not very fluent with SQL so could someone tell me what's wrong with the code that makes it output this error? 我不明白该错误消息,因为我不太懂SQL,所以有人可以告诉我输出该错误的代码有什么问题吗? Thanks. 谢谢。

I'm not sure how, if at all, Eloquent handles composite keys. 我不确定Eloquent如何处理复合键(如果有的话)。 That said, your error message is coming out of MySQL. 就是说,您的错误消息来自MySQL。 The cryptic error 150 usually has something to do with an ill formed foreign key constraint. 隐秘错误150通常与格式错误的外键约束有关。

If your case above, it looks like the work_id foreign key in slides is not the same type as the id you're trying to match it with. 如果是上述情况,则slideswork_id外键看起来与您要与其匹配的id类型不同。 While both columns are int s, one is int(10) , the other is int(11) . 虽然两列都是int ,但一列是int(10) ,另一列是int(11) It also appears one is UNSIGNED and the other is signed. 它还显示一个是未UNSIGNED ,另一个是已签名的。

If you can fiddle with your migrations so both columns are identical, you should be able to solve this specific foreign key problem. 如果您可以摆弄迁移,使两列都相同,那么您应该能够解决此特定的外键问题。

The only thing that comes to my mind that could case problem is your primary key. 我想到的唯一可能会出现问题的事情是您的主键。

You should try to change: 您应该尝试更改:

$table->primary(['id', 'work_id']);

into

$table->primary('id');

to check if it's working now 检查它现在是否正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM