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

时间:2021-01-21 17:53:01

标签: php laravel-8

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


类别表

<头>
id 姓名
1 体育
2 技术
 public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id('id');
            $table->string('name');
        });

    }
?>

用户

<头>
id 姓名 电子邮件
1 法赫德 f@f.com
2 约翰 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 -> 透视表

<头>
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`))

2 个答案:

答案 0 :(得分:2)

请先阅读文档。
https://laravel.com/docs/8.x/migrations#foreign-key-constraints

<块引用>

foreignId 方法是 unsignedBigInteger 的别名,而 constrained 方法将使用约定来确定被引用的表名和列名。如果您的表名与 Laravel 的约定不匹配,您可以通过将其作为参数传递给 constrained 方法来指定表名:

问题在于您将表名提供为 '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');

答案 1 :(得分:0)

使用 cascadeOnDelete() 方法定义级联

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