添加嵌套商品条目至购物车时出现“Product could not be found”错误及商品信息缺失问题求助
添加嵌套商品条目至购物车时出现“Product could not be found”错误及商品信息缺失问题求助
看起来你遇到了两个核心问题:一是虚拟bundle容器引发的“Product could not be found”错误,二是子商品仅显示ID、缺失其他关键信息。我来帮你一步步排查和解决:
一、解决“Product could not be found”错误
你当前创建的容器行项目用了LineItem::PRODUCT_LINE_ITEM_TYPE,这个类型要求关联真实存在的商品ID——但你用的是字符串'bundle',Shopware会自动尝试去查找这个ID对应的商品,自然找不到而报错。
正确的做法是把容器设为自定义行项目类型,不需要关联真实商品:
// 用UUID生成唯一的行项目ID,避免冲突 use Symfony\Component\Uid\Uuid; $containerLineItem = new LineItem( Uuid::randomHex(), LineItem::CUSTOM_LINE_ITEM_TYPE, // 自定义类型,不关联真实商品 null, 1 ); // 给容器设置一个显示名称,方便前端识别 $containerLineItem->setLabel('Custom Bundle');
二、解决子商品信息缺失问题
你提到$nestedLineItems里只有商品ID,说明你的getLineItem()方法只是创建了空的LineItem对象,没有从数据库加载商品的完整数据(价格、封面、描述等)。
你需要借助Shopware的ProductRepository和LineItemFactory来生成完整的商品行项目:
- 首先在控制器中注入这两个服务:
use Shopware\Core\Content\Product\ProductRepository; use Shopware\Core\Checkout\Cart\LineItemFactory\LineItemFactory; private $productRepository; private $lineItemFactory; public function __construct(ProductRepository $productRepository, LineItemFactory $lineItemFactory) { $this->productRepository = $productRepository; $this->lineItemFactory = $lineItemFactory; }
- 重写
getLineItem()方法,加载完整商品数据并生成标准行项目:
private function getLineItem(string $productId, SalesChannelContext $context): LineItem { // 从数据库查询商品实体 $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$productId]); $product = $this->productRepository->search($criteria, $context)->first(); if (!$product) { // 可以抛出自定义异常,或者跳过该商品 throw new \Shopware\Core\Content\Product\Exception\ProductNotFoundException($productId); } // 用LineItemFactory生成包含完整信息的行项目 return $this->lineItemFactory->create( $product, 1, // 商品数量,可根据需求从$lineItemBag获取 [], // 可选:商品的自定义配置(比如规格选项) $context ); }
三、其他优化建议
- 移除重复的购物车查询:你的方法参数已经传入了
Cart $cart,不需要再调用$this->cartService->getCart(),直接用参数里的$cart即可,减少不必要的数据库查询。 - 输入验证:在循环处理
$lineItemIds时,先验证$lineItemBag->get('id')是否是有效的商品ID格式(比如UUID),避免无效ID导致的错误。 - 错误处理:给单个商品的加载过程添加try-catch,比如某个商品不存在时,跳过它并记录日志,而不是直接抛出异常中断整个流程。
- 容器价格设置:如果虚拟bundle不需要单独定价,可以设置容器价格为0,或者将子商品的总价汇总到容器上(根据你的业务需求):
$totalPrice = $nestedLineItems->getPrices()->getTotalPrice(); $containerLineItem->setPrice(new \Shopware\Core\Checkout\Cart\Price\Price($totalPrice, $totalPrice, $totalPrice));
备注:内容来源于stack exchange,提问作者Jacky Raimond
相关产品推荐
相关产品推荐

