【问题标题】:How to create 2 foreign keys with Laravel migration如何使用 Laravel 迁移创建 2 个外键
【发布时间】:2018-05-16 07:30:54
【问题描述】:

我有 letter 的模型,这个模型有 2 个来自附件和联系人的外键

public function up()
{
    Schema::create('letters', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('contact_id')->unsigned();
        $table->integer('attachment_id')->unsigned();
        $table->timestamps();
        $table->foreign('contact_id')->references('id')->on('contacts');
        $table->foreign('attachment_id')->references('id')->on('attachments');
    });
}

这是我迄今为止尝试过的。但是当我输入工匠迁移 SQL 时,我收到以下错误

一般错误:1005 无法创建表 ss.#sql-1064_4a (errno: 150 "Foreign
键约束格式不正确”)(SQL:alter table letters 添加约束 letters_attach
ment_id_foreign
外键 (attachment_id) 引用 attachments (id))

【问题讨论】:

  • 您能否显示contacts 和attachments 表的迁移?

标签: laravel-5 foreign-keys database-migration


【解决方案1】:

首先创建表行,然后添加伪造键。

   Schema::create('letters', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('contact_id')->unsigned();
        $table->integer('attachment_id')->unsigned();
        $table->timestamps();
    });
       Schema::table('letters', function (Blueprint $table) {
           $table->foreign('contact_id')->references('id')->on('contacts');
        $table->foreign('attachment_id')->references('id')->on('attachments');
        });

我想这会起作用

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 2023-01-04
    • 2021-12-31
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2016-12-07
    • 2018-11-10
    相关资源
    最近更新 更多