1、前言:ERP系统,一个基准产品库(基准库),一个可售产品库(可售库),一条可售库商品sku可以对应一条/多条基准库商品SKU。
三个数据表
product_items(基准库)
seller_product_items(可售库)
seller_product_item_mappings(多对多关联表)
2、需求:在进行组合可售商品时(可售商品和基准进行关联),如果在关联表里已经存在当前提交的组合时则提示该组合已存在。
3、代码
参数示例
{
"items": {
"0": {
"sku": "MD8009-W-BlackL",
"amount": 1
},
"1": {
"sku": "MD8009-W-NudeL",
"amount": 1
}
}
}
/**
* 去重(判断当前组合是否存在)
*
* @param array $items
* @return bool
*/
public function checkDuplicates(array $items)
{
$productItemIds = $this->productItem
->whereIn('sku', Arr::pluck($items, 'sku'))
->pluck('id', 'sku');
// 这里直接用DB操作中间表,ORM特别慢
$query = DB::table('seller_product_item_mappings');
foreach ($items as $key => &$item) {
if ($id = Arr::get($productItemIds, $item['sku'])) {
$item['product_item_id'] = $id;
} else {
throw new ProductException(422, '基准产品' . $item['sku'] . '未创建');
}
if ($key == 0) {
$query->whereRaw('product_item_id=? and amount=?', [$item['product_item_id'], $item['amount']]);
} else {
$query->orWhereRaw('product_item_id=? and amount=?', [$item['product_item_id'], $item['amount']]);
}
}
$sellerProductItemId = $query->groupBy('seller_product_item_id')
->havingRaw('COUNT(seller_product_item_id) = ?', [count($items)])
->value('seller_product_item_id');
if ($sellerProductItemId) {
$count = DB::table('seller_product_item_mappings')
->where('seller_product_item_id', $sellerProductItemId)
->count();
if ($count == count($items)) {
$sku = $this->sellerProductItem
->where('id', $sellerProductItemId)
->value('sku');
return $sku;
} else {
// 不存在该项,可以创建关联
return false;
}
}
}