【问题标题】:How to create a pivot table laravel?如何创建数据透视表 laravel?
【发布时间】:2023-03-16 14:51:01
【问题描述】:

我有一个简单的博客,其中有一个包含标题和标签的帖子,现在我希望用户能够添加标签,根据我需要使用名称约定创建数据透视表的文档。

PHPMyAdmin 上的帖子表

id   title
1    Death
2    Love

PHPMyAdmin 上的标签表

id   name

这是我创建数据透视表的迁移

<?php

class CreatePostTagTable extends Migration
{
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('post_id')->unsigned();
            $table->foreign('post_id')->references('id')->on('posts');
            $table->integer('tag_id')->unsigned();
            $table->foreign('tag_id')->references('id')->on('tags');
        });
    }

    public function down()
    {
        Schema::dropIfExists('post_tag');
    }
}

现在,当我运行 PHP artisan migrate 时,出现以下错误。

 SQLSTATE[HY000]: General error: 1005 Can't create table `royalad`.`#sql-ee8_307` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `post_tag` add constraint `post_tag_post_id_foreign` foreign key (`post_id`) references `posts` (`id`)) 

我的代码做错了什么?

【问题讨论】:

    标签: php mysql laravel laravel-blade


    【解决方案1】:

    在您的tag_id 中也将$table-&gt;integer('post_id')-&gt;unsigned(); 更改为$table-&gt;bigInteger('post_id')-&gt;unsigned();

    【讨论】:

    • 因为外键必须与本地键匹配格式
    • 顺便说一句,创建数据透视表时根本不需要外键
    • 非常感谢解决了这个问题,他们应该将此添加到文档中,对于新手会有用
    • 我们一直向文档发送拉取请求,但他们拒绝了它¯\_(ツ)_/¯
    猜你喜欢
    • 2013-03-27
    • 2019-06-06
    • 1970-01-01
    • 2020-02-06
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多