在创建时使用数据透视列附加资源

问题描述 投票:0回答:1

product
contracts
,两者都有
many to many
关系,我在
contracts
nova资源中添加了以下内容。

BelongsToMany::make('Products', 'products', Products::class)
                 ->fields(function () {
                     {
                       return [
            Currency::make('Contract Price')
                ->dependsOn(['products'], function (Currency $field, NovaRequest $request, FormData $formData) {
                  $selectedProductId = $formData->products;
                  if ($selectedProductId) {
                      $product = ProductModel::find($selectedProductId);
                      $field->value = $product->price;
                  }
           }),
        ];
   }),

但是,只有在创建合同后才能附加此信息。我想检查是否可以在创建合同时附加产品,并能够添加作为数据透视列的合同价格。

根据以下问题给出的答案,它不允许我添加数据透视列值。 https://stackoverflow.com/a/66359524/10535590

laravel-nova
1个回答
0
投票

在您

Contract
模型文件中:

// Define a property for temporary storage
protected $defaultProductId;

public function getDefaultProductId() {
    return $this->defaultProductId;
}

public function setDefaultProductId($productId) {
    $this->defaultProductId = $productId;
}

public function contract(): BelongsTo {
   return $this->belongsTo(Contract::class);
}

// hook into the saving and post save (created)
protected static function boot() {
        parent::boot();
        static::creating(function ($contract) {
            $productId = $contract->attributes['product_id'] ?? false;
            unset($contract->attributes['product_id']);
            $contract->setDefaultProductId($productId);
        });

        static::created(function ($contract) {
            $productId = $contract->getDefaultProductId() ?? false;
            if ($productId) {
                $product = Product::find($productId);

                if ($product && !$product->contracts()->where('contract_id', $contract->id)->exists()) {
                    // Attach
                    $contract->products()->attach($productId, ['contract_price' => $product->price]);
                }
            }
        });
    }

在您的

Contract
资源文件中:

 BelongsTo::make(__('Product'), 'product', Product::class)
                ->searchable()->showOnCreating(),

如果您也需要

Product
上的关系,您可以执行相反的操作

© www.soinside.com 2019 - 2024. All rights reserved.