【问题标题】:Laravel Pivot model with extra attributes具有额外属性的 Laravel Pivot 模型
【发布时间】:2020-10-15 12:37:05
【问题描述】:

我有物品目录管理系统。

目录项(型号):

 Schema::create('catalog_items', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->float('price');
        $table->float('deposit')->nullable();
        $table->timestamps();
    });

定价(型号):

 Schema::create('pricings', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name',127);
        $table->boolean('enable')->default(true);
        $table->timestamps();
    });

CatalogItemPricingPivot(枢轴模型):

Schema::create('catalog_item_pricing', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('catalog_item_id');
        $table->bigInteger('pricing_id');
        $table->float('discount')->nullable()->default(0);
        $table->timestamps();
    });

现在,当我想更新 CatalogItem 的定价时,我会这样做:

$CatalogItem->pricings()->sync([
    1 => array:1 [
        "discount" => "25.00"
    ]
]);

这也可以

 $CatalogItem->pricings()->sync([
    1 => array:1 [
        "discount" => "25.00"
    ],
    5 => array:1 [
        "discount" => "12.25"
    ]
]);

如果我在观察者中打印模型,我不会在原件中获得折扣字段

 public function boot()
{

    CatalogItemPricingPivot::updated(function($model){
        dd($model);
    });
}

结果

App\Pivots\CatalogItemPricingPivot {
  table: "catalog_item_pricing"
  exists: true
  wasRecentlyCreated: false
  attributes: array:4 [
    "catalog_item_id" => 172
    "pricing_id" => 1
    "discount" => "25.00"
  ]
  original: array:2 [
    "catalog_item_id" => 172
    "pricing_id" => 1
  ]
  changes: array:2 [
    "discount" => "25.00"
  ]
  casts: []
}

它似乎改变了一点而不是。

如何在同步后获得带有额外字段的数据透视表的真正更改?

编辑:

MAIN 的目的是让 CatalogItemPricingPivot 在哪里更新

谢谢。

【问题讨论】:

    标签: php laravel many-to-many pivot-table


    【解决方案1】:

    要更新已附加的数据透视数据,您应该使用updateExistingPivot 方法。 https://laravel.com/docs/8.x/eloquent-relationships#updating-many-to-many-relationships

    而不是

    $CatalogItem->pricings()->sync([
        1 => array:1 [
            "discount" => "25.00"
        ]
    ]);
    

    试试这个

    $CatalogItem->pricings()->each(function ($pricing) use ($CatalogItem) {
        $CatalogItem->pricings()->updateExistingPivot($pricing, [
            "discount" => "23.00"
        ]);
    });
    

    【讨论】:

    • 新支点怎么样?
    • 是的,但我也在使用同步来分离
    • 所以我需要两种情况,首先同步然后更新ExistingPivot
    • 在每个之后我怎么知道数据透视表是否改变了?
    【解决方案2】:

    在 upwork 上看到你的帖子。

    尝试将->withPivot('discount'); 添加到关系中

    【讨论】:

    • 有 $this->belongsToMany(Pricing::class) ->using(CatalogItemPricingPivot::class) ->withPivot('discount') ->withTimestamps();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2016-02-04
    • 2016-05-17
    • 1970-01-01
    相关资源
    最近更新 更多