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
在您
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
上的关系,您可以执行相反的操作