You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6.4购物车验证器getQuantityInformation始终返回NULL但var_dump正常

购物车验证器中getQuantityInformation()返回NULL的问题解决

我有一款自定义产品,添加至购物车后,希望在结账前验证购物车,确保该自定义产品符合特定条件。参考Shopware官方文档的添加购物车验证器实现了CustomCartValidator类,但遇到问题:代码中$lineItem->getQuantityInformation()始终返回NULL,但用var_dump($lineItem->getQuantityInformation())却能输出正确信息。

实现代码

class CustomCartValidator implements CartValidatorInterface
{
    public function validate(Cart $cart, ErrorCollection $errorCollection, SalesChannelContext $salesChannelContext): void
    {
        foreach ($cart->getLineItems()->getFlat() as $lineItem) {
          if($lineItem->getQuantityInformation() === null){
            continue;
          }
          
          //use the quantity information here

        }
    }
}

问题原因

这是因为Shopware购物车线项的quantityInformation字段存在延迟加载机制,默认调用getQuantityInformation()时不会主动从数据库加载完整数据;而var_dump会直接读取对象的底层属性,不受getter的加载逻辑限制,所以能输出正确信息。

解决方法

1. 强制加载数量信息

调用getQuantityInformation()时传入true参数,强制触发数据加载:

foreach ($cart->getLineItems()->getFlat() as $lineItem) {
    // 传入true强制加载完整数量信息
    $quantityInfo = $lineItem->getQuantityInformation(true);
    if($quantityInfo === null){
        continue;
    }
    
    // 在此使用数量信息
}

2. 过滤非产品类线项

只处理产品类型的线项,避免无数量信息的线项干扰:

use Shopware\Core\Checkout\Cart\LineItem\LineItem;

foreach ($cart->getLineItems()->getFlat() as $lineItem) {
    // 跳过非产品类型的线项(如促销、运费)
    if ($lineItem->getType() !== LineItem::PRODUCT_LINE_ITEM_TYPE) {
        continue;
    }
    
    $quantityInfo = $lineItem->getQuantityInformation(true);
    if($quantityInfo === null){
        continue;
    }
    
    // 在此使用数量信息
}

3. 调整验证器执行优先级

在插件的services.xml中设置验证器的较低优先级(数值越大越晚执行),确保线项数据已被完整初始化:

<service id="YourPlugin\Cart\CustomCartValidator" >
    <tag name="shopware.cart.validator" priority="100" />
</service>

内容的提问来源于stack exchange,提问作者Templator Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 16:28:23