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

Magento 2.4如何获取所有UpSells产品集合

获取所有Upsell产品的实现方案

完全可以通过Collection或SearchCriteria两种方式实现Upsell产品的获取,以下是具体实现方法:

一、使用Product Collection(适用于Magento 1/2)

通过目标产品模型直接加载其关联的Upsell产品集合,可按需过滤启用状态的产品:

$targetProductId = 123; // 替换为你的目标产品ID
$product = \Magento\Framework\App\ObjectManager::getInstance()
    ->create(\Magento\Catalog\Model\Product::class)
    ->load($targetProductId);

// 获取Upsell产品集合
$upsellCollection = $product->getUpSellProductCollection()
    ->addAttributeToSelect(['name', 'price', 'sku']) // 按需指定需要的属性,避免全量加载
    ->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
    ->setPageSize(50); // 分页限制,防止性能问题

// 遍历处理Upsell产品
foreach ($upsellCollection as $upsellItem) {
    echo "Upsell产品:{$upsellItem->getName()},SKU:{$upsellItem->getSku()}";
}

二、使用SearchCriteria(Magento 2 推荐的API风格)

通过产品链接仓库构建查询条件,获取指定类型的关联产品:

use Magento\Catalog\Api\ProductLinkRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Model\ProductLink\LinkTypeProviderInterface;

$targetProductId = 123;
$upsellLinkType = LinkTypeProviderInterface::LINK_TYPE_UPSELL;

// 依赖注入方式获取实例(生产环境推荐)
$productLinkRepo = \Magento\Framework\App\ObjectManager::getInstance()
    ->create(ProductLinkRepositoryInterface::class);
$searchCriteriaBuilder = \Magento\Framework\App\ObjectManager::getInstance()
    ->create(SearchCriteriaBuilder::class);

// 构建查询条件
$searchCriteria = $searchCriteriaBuilder
    ->addFilter('product_id', $targetProductId)
    ->addFilter('link_type', $upsellLinkType)
    ->create();

// 获取Upsell产品链接列表
$upsellLinks = $productLinkRepo->getList($searchCriteria)->getItems();

foreach ($upsellLinks as $link) {
    $upsellProductId = $link->getLinkedProductId();
    // 加载产品详情
    $upsellProduct = \Magento\Framework\App\ObjectManager::getInstance()
        ->create(\Magento\Catalog\Model\Product::class)
        ->load($upsellProductId);
    
    echo "Upsell产品ID:{$upsellProductId},名称:{$upsellProduct->getName()}";
}

注意事项

  • 生产环境禁止直接使用ObjectManager,应通过依赖注入注入所需类实例。
  • 避免使用addAttributeToSelect('*'),按需指定属性可大幅提升查询性能。
  • 如果需要获取全站点所有产品的Upsell关联,可遍历所有产品ID分别查询,或直接查询catalog_product_link表(link_type_id对应Upsell的ID,可通过LinkTypeProviderInterface动态获取)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:27:16