简体   繁体   中英

Laravel Error when creating composite foreign key

I need to build a table named 'slides' that contains two columns named 'id' and 'work_id'. The ID is not an AUTO_INCREMENT integer because I need to keep the numbers as the index inside a slideshow.

This is the error that is displayed when running 'php artisan migrate': 错误

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? Thanks.

I'm not sure how, if at all, Eloquent handles composite keys. That said, your error message is coming out of MySQL. The cryptic error 150 usually has something to do with an ill formed foreign key constraint.

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. While both columns are int s, one is int(10) , the other is int(11) . It also appears one is UNSIGNED and the other is signed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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