如何用Laravel迁移创建2个外国钥匙



我有字母的模型,该模型有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"外国
密钥约束形成不正确")(SQL:ALTE表letters添加约束letters_attach
ment_id_foreign
外键(attachment_id)参考attachmentsid))

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

   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');
        });

我猜这将有效

最新更新