【问题标题】:Laravel - Add column to existing pivot table and add MUL keyLaravel - 将列添加到现有数据透视表并添加 MUL 键
【发布时间】:2018-02-23 18:38:34
【问题描述】:

我有一个 Laravel 数据透视表,其中包含多个主键:“order_id”、“product_id”、“variation_id”。

我需要在此表中添加一个名为“id”的新列,如下所示:

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

我的原始迁移文件如下所示:

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

此迁移包括我的 3 个复合键。

我现在需要添加新列“id”并将此列添加到复合键中。

我在 Laravel 文档中找不到任何内容,并且怀疑这可能是不可能的,因为它可能会影响此表中过去的记录。

【问题讨论】:

    标签: php sql laravel


    【解决方案1】:

    你可以删除主键然后创建一个新的:

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

    【讨论】:

      猜你喜欢
      • 2019-06-12
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      相关资源
      最近更新 更多