Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

php - (Laravel 8) errno: 150 "Foreign key constraint is incorrectly formed

I want to create a table that assists users to read the topics that order by categories; also, users select the categories that they want in order to see the interest topics associated with categories. For instance, when users go to BBC, they can see the topics that they want to see from categories.


categories Table


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Please read the documentation first.
https://laravel.com/docs/8.x/migrations#foreign-key-constraints

The foreignId method is an alias for unsignedBigInteger while the constrained method will use conventions to determine the table and column name being referenced. If your table name does not match Laravel's conventions, you may specify the table name by passing it as an argument to the constrained method:

The issue is that you're providing the table name as 'cascade' instead of 'users'.
i.e

//Should be...
$table->foreignId('user_id')->constrained('users');
//Instead of...
$table->foreignId('user_id')->constrained('cascade');

Don't forget to correct the 'category_id' as well.

If you really wish to apply 'cascade' options, try:

$table->foreignId('user_id')
      ->constrained()
      ->onUpdate('cascade')
      ->onDelete('cascade');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...