(Laravel 8) errno: 150 "外键约束的格式不正确

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

我想创建一个 table 来帮助用户阅读按类别排序的主题;此外,用户 select 他们想要的类别,以便查看与类别相关的兴趣主题。例如,当用户访问 BBC 时,他们可以从类别中看到他们想看的主题。


类别Table

id name
1 sports
2 Tech
 public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id('id');
            $table->string('name');
        });

    }
?>

用户

id name email
1 Fahad f@f.com
2 Jhon Jho@h.com
 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('username')->unique();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('avatar')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }


category_user -> 枢轴 table

id user_id category_id
1 1 2
2 2 1
 public function up()
    {
        Schema::create('category_user', function (Blueprint $table) {
            $table->foreignId('user_id')->constrained('cascade');
            $table->foreignId('category_id')->constrained('cascade');
        });
    }

类别 -> 型号

    public function User(){
        return $this->belongsToMany(User::class);
    }

错误

  SQLSTATE[HY000]: General error: 1005 Can't create table `athar_db`.`category_user` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `category_user` add constraint `category_user_user_id_foreign` foreign key (`user_id`) references `cascade` (`id`))

使用cascadeOnDelete()方法定义级联

$table->foreignId('user_id')->constrained()->cascadeOnDelete() 

请先阅读文档。
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:

问题是您提供的 table 名称 作为 'cascade' 而不是 'users'.

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

别忘了更正 'category_id'

如果您真的想应用 'cascade' 选项,请尝试:

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