Laravel迁移 - 不适用于表的外键

时间:2017-01-20 17:07:15

标签: php laravel laravel-migrations

我尝试使用迁移添加外键约束。迁移完成没有任何错误。但是,选中数据库时,外键约束不会添加到表中。除了FK约束之外,迁移中指定的其他内容工作正常。

我的FKs透视表:

Schema::create('book_author', function (Blueprint $table) {

            $table->integer('book_id')->unsigned();
            $table->integer('author_id')->unsigned();

            $table->foreign('book_id')->references('id')->on('book')->onDelete('restrict')->onUpdate('cascade');
            $table->foreign('author_id')->references('id')->on('author')->onDelete('restrict')->onUpdate('cascade');
            $table->primary(['book_id','author_id']);

        });
        Schema::enableForeignKeyConstraints();

作者表:

Schema::create('author', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email', 250)->unique();
        });

书桌:

 Schema::create('book', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
        });

我在这里找不到任何东西?

2 个答案:

答案 0 :(得分:0)

book_author 迁移更改为:

Schema::create('book_author', function (Blueprint $table) {
    $table->integer('book_id')->unsigned()->index();
    $table->integer('author_id')->unsigned()->index();

    $table->foreign('book_id')->references('id')->on('book')->onDelete('cascade')->onUpdate('cascade');
    $table->foreign('author_id')->references('id')->on('author')->onDelete('cascade')->onUpdate('cascade');
});

这应该有用。

另一方面,你用表名破坏了一些Laravel约定:

  1. 以复数形式命名您的表格(作者& 图书
  2. 应调用数据透视表( book_author )( author_book ) - 按字母顺序排列的优先级

答案 1 :(得分:0)

MyISAM不支持外键:http://dev.mysql.com/doc/refman/5.7/en/myisam-storage-engine.html

运行以下命令以确定您的表具有哪个引擎:

SHOW TABLE STATUS WHERE Name = 'book_author'

如果显示MyISAM,则有两个选项:

  1. 不要使用FK
  2. 更换引擎
  3. 我会使用选项2,因为您正在创建一个新表,并且没有丢失数据的风险。

    您可以使用以下方式强制迁移:

    $table->engine = 'InnoDB';
    

    或者,您可以手动运行此命令:

    ALTER TABLE book_author ENGINE=INNODB