首页 > 解决方案 > 如何创建数据透视表 laravel?

问题描述

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

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

我的代码做错了什么?

标签: phpmysqllaravellaravel-blade

解决方案


改成$table->integer('post_id')->unsigned();$table->bigInteger('post_id')->unsigned();tag_id也。


推荐阅读