【发布时间】:2019-10-21 12:58:51
【问题描述】:
我有一个问题好几天没能解决。也许这里有人可以帮助我。
基本思路
我有一个名为 Product 的模型。每个Product 可以有多个ProductAttributes(belongsToMany 带有枢轴)。
例子:
Product:汽车
-
ProductAttributes:- 颜色
- 马力
ProductAttribute 的数据透视表包含各个属性的值(颜色 = 蓝色,PS = 180)。
这已经很好用了。
问题
现在我想实现产品包。一个产品包 (ProductBundle) 包含许多产品。但是这些产品应该有自己的属性数据透视表。因此,在一个产品包中,我希望能够指定我创建的汽车的 PS 比实际产品中定义的要多。
为此,我需要 2 个属性数据透视表。
我已经尝试过的
-
ProductBundlebelongsToManyProduct使用不同的数据透视表 -
ProductBundlebelongsToManyProductBundleProduct(ProductBundleProduct有一个名为product_id的字段,它指的是实际的“基本产品”)
在这两种情况下,我都有一个问题,即属于产品包的产品属性的数据透视表未正确保存:
产品
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function productBundleAttributes()
{
return $this->belongsToMany(ProductAttribute::class,
product_bundle_product_attribute')
->withPivot($this->attributefields)-> withTimestamps();
}
控制器
$prod = Product::findOrFail($product['id']);
$added = $productbundle->products()->save($prod, [
'custom' => $product['custom'],
'title' => $product['title'],
# 'factor' => $product['factor']
]);
/*Save attributes*/
$added->syncProductBundleAttributes($product['attributes']],
$productbundle->id);
同步方法
public function syncProductBundleAttributes(
array $attributes,
int $id
) {
$this->checkProductAttributesRecursively(collect($attributes)->transform(function (
$attributes
) use (
$id
) {
$attribute['product_bundle_id'] = $id;
$attribute['product_attribute_id'] = $attribute['id'];
return $attribute;
})->toArray());
$this->productBundleAttributes()->attach($this->result);
return $this->result;
}
不幸的是,这意味着一次只存储一个属性。
【问题讨论】:
标签: laravel eloquent laravel-6 laravel-6.2