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

Shopware 6.5中如何通过order_line_item.repository获取订单商品明细?

正确获取Shopware 6.5订单商品列表的方法

问题根源

你错误地使用客户的VersionId作为订单项的查询条件,订单项与订单直接关联,筛选条件应该是订单ID,这才是导致查询结果为空的原因。

方法一:直接从Order对象加载关联获取

如果事件中的Order对象未自动加载lineItems关联(Shopware默认懒加载),可以通过AssociationLoader手动加载关联,之后直接遍历获取SKU:

use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Association\AssociationLoader;

// 确保已注入AssociationLoader $associationLoader
$order = $event->getOrder();

// 加载订单的lineItems关联,同时嵌套加载product关联以获取商品编号
$associationLoader->load(
    $order,
    (new Criteria())->addAssociation('lineItems.product'),
    $event->getContext()
);

// 遍历商品类型的订单项
foreach ($order->getLineItems() as $lineItem) {
    // 仅处理商品类型的订单项,排除运费、折扣等类型
    if ($lineItem->getType() === 'product') {
        $orderRow = [
            "sku" => $lineItem->getProduct()->getProductNumber()
        ];
        // 后续业务逻辑处理
    }
}

方法二:通过order_line_item.repository查询

使用仓库查询时,需指定正确的筛选条件并关联加载商品信息:

use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;

$orderId = $event->getOrder()->getId();
$criteria = new Criteria();

// 筛选当前订单下的订单项
$criteria->addFilter(new EqualsFilter('orderId', $orderId));
// 仅保留商品类型的订单项
$criteria->addFilter(new EqualsFilter('type', 'product'));
// 关联加载product实体,否则无法获取商品编号
$criteria->addAssociation('product');

$orderLineItems = $this->orderLineItemRepository
    ->search($criteria, $event->getContext())
    ->getEntities();

// 遍历提取SKU
foreach ($orderLineItems as $lineItem) {
    $orderRow = [
        "sku" => $lineItem->getProduct()->getProductNumber()
    ];
    // 后续业务逻辑处理
}

关键注意事项

  • 订单项包含多种类型(product/shipping/discount等),必须通过type筛选确保只处理商品项,避免调用getProduct()返回null导致报错。
  • 查询时必须显式添加addAssociation('product'),否则商品关联不会被加载,无法获取商品编号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:27:38