id)->delete(); } /** * 根据规格生成SKU * * @param Goods $goods 商品 * @param array $options {spec: 指定规格, price: 基础价格, name: 基础名称, stock: 默认库存, name_add: 是否在名称上面追加属性值, price_add: 是否在价格上面追加属性的加价} */ public function generateSku(Goods $goods, $options = []) { $spec = data_get($options, 'spec', $goods->spec); $price = floatval(data_get($options, 'price', $goods->price)); $name = data_get($options, 'name', $goods->name); $stock = intval(data_get($options, 'stock', $goods->stock)); $nameAdd = (bool) data_get($options, 'name_add', false); $priceAdd = (bool) data_get($options, 'price_add', false); if ($spec) { $specList = []; foreach ($spec as $item) { $items = []; foreach ($item['values'] as $value) { array_push($items, [ 'name' => $item['name'], 'value' => $value['name'], 'price' => floatval($value['value']), ]); } array_push($specList, $items); } $cartesianList = Arr::crossJoin(...$specList); foreach ($cartesianList as $items) { $specPrice = $priceAdd ? $price + array_sum(array_column($items, 'price')) : $price; $specName = $nameAdd ? $name.' '.implode(' ', array_column($items, 'value')) : $name; $exists = $goods->skus()->jsonArray($items)->exists(); $attributes = [ 'name' => $specName, 'price' => $specPrice, 'stock' => $stock, 'spec' => $items, ]; if ($exists) { $goods->skus()->jsonArray($items)->update($attributes); } else { $attributes['sn'] = $this->generateSn(); $goods->skus()->create($attributes); } } } } }