Laravel多对多关联查询(ERP系统)

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;
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值