【问题标题】:belongsToMany withPivot that belongs to another item with pivotbelongsToMany withPivot 属于另一个具有枢轴的项目
【发布时间】:2019-10-21 12:58:51
【问题描述】:

我有一个问题好几天没能解决。也许这里有人可以帮助我。

基本思路

我有一个名为 Product 的模型。每个Product 可以有多个ProductAttributesbelongsToMany 带有枢轴)。

例子:

Product:汽车

  • ProductAttributes:
    • 颜色
    • 马力

ProductAttribute 的数据透视表包含各个属性的值(颜色 = 蓝色,PS = 180)。

这已经很好用了。

问题

现在我想实现产品包。一个产品包 (ProductBundle) 包含许多产品。但是这些产品应该有自己的属性数据透视表。因此,在一个产品包中,我希望能够指定我创建的汽车的 PS 比实际产品中定义的要多。

为此,我需要 2 个属性数据透视表。

我已经尝试过的

  • ProductBundle belongsToMany Product 使用不同的数据透视表
  • ProductBundle belongsToMany ProductBundleProductProductBundleProduct 有一个名为 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


    【解决方案1】:

    您可以在 ProductProductAttributes 之间的数据透视表中添加一个列,例如 product_bundle_id。因此,您可以通过这种方式获取特定捆绑包的属性,或 product_bundle_id 为 0 的基本属性

    Laravel Eloquent, Many to Many中查看Saving Additional Data On A Pivot Table

    【讨论】:

    • 嗨。如果一个捆绑包包含 2 个相同的产品(例如具有不同的枢轴),这将不起作用,因为 product_bundle_id 将是相同的,对吗?套装包含:产品:汽车(带枢轴:颜色 = 黑色) 产品:汽车(带枢轴:颜色 = 蓝色)
    • 然后使用product_bundle_product_id,并将hasMany 用于BundleBundleProduct
    猜你喜欢
    • 2018-08-28
    • 2012-09-23
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2016-07-08
    • 2016-08-13
    • 2019-05-31
    • 2020-04-25
    相关资源
    最近更新 更多