如何使用laravel migration创建2 forign键

时间:2017-12-02 08:54:14

标签: laravel-5 database-migration

我有信函的模型,这个模型有两个来自附件和联系人的忘记密钥

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

我这样做。但是当我输入artisan migration SQL时出错

常规错误:1005无法创建表格ss#sql-1064_4a(错误号码:150&#34;异物<   键约束形成错误&#34;)(SQL:alter table letters添加约束letters_attach
ment_id_foreign
外键(attachment_id)引用attachmentsid))< / p>

1 个答案:

答案 0 :(得分:1)

首先创建表行,然后添加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');
        });

我想这会起作用