简体   繁体   English

Laravel-将列添加到现有数据透视表并添加MUL键

[英]Laravel - Add column to existing pivot table and add MUL key

I have a Laravel pivot table which contains multiple primary keys: "order_id", "product_id", "variation_id". 我有一个Laravel数据透视表,其中包含多个主键:“ order_id”,“ product_id”,“ variation_id”。

I need to add a new column called "id" to this table which I do as follows: 我需要在此表中添加一个名为“ id”的新列,其操作如下:

public function up()
    {
        Schema::table('order_product', function (Blueprint $table) 
        {
            $table->integer('id')->unsigned()->after('variation_sku');
        });
    }

My original migration file looks as follows: 我的原始迁移文件如下所示:

public function up()
    {
        Schema::create('order_product', function (Blueprint $table) 
        {
            $table->integer('order_id')->unsigned()->index();
            $table->foreign('order_id')->references('order_id')->on('orders')->onDelete('cascade');
            $table->integer('product_id')->unsigned()->index();
            $table->foreign('product_id')->references('product_id')->on('products')->onDelete('cascade');
            $table->integer('variation_id')->unsigned()->index()->nullable();
            $table->jsonb('variation')->nullable();
            $table->integer('qty');
            $table->string('variation_status')->default('bakery');
            $table->timestamps();
            $table->softDeletes();
            $table->primary(['order_id', 'product_id', 'variation_id']);
        });
    }

This migration includes my 3 composite keys. 此迁移包括我的3个复合键。

I now need to add the new column "id" and add this column to the composite keys. 现在,我需要添加新列“ id”,并将此列添加到组合键中。

I cannot find anything in the Laravel documentation and have a suspicion that this may not be possible as it may affect past records in this table. 我在Laravel文档中找不到任何内容,并且怀疑这可能是不可能的,因为它可能会影响此表中的过去记录。

You could drop the primary key then create a new one: 您可以删除主键,然后创建一个新的:

public function up()
{
    Schema::table('order_product', function (Blueprint $table) 
    {
        $table->integer('id')->unsigned()->after('variation_sku');
        $table->dropPrimary();
        $table->primary(['id', 'order_id', 'product_id', 'variation_id']);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM