加入二手产品进行产品收集

Join used products for products collection

我一直在为我的问题寻找解决方案,但没有效果。

我想列出简单的可配置产品和可配置的二手产品。问题在于性能,因为要获得二手产品,我必须使用这种方法:

Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product)

仅属于一项。您可以想象,对于很多产品,有大量的 SQL 查询。如何进行向集合添加 used_products 属性的查询?

文件中您正在使用的同一模型中还有另一个函数app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php :

public function getUsedProductCollection($product = null)
{
    $collection = Mage::getResourceModel('catalog/product_type_configurable_product_collection')
        ->setFlag('require_stock_items', true)
        ->setFlag('product_children', true)
        ->setProductFilter($this->getProduct($product));
    if (!is_null($this->getStoreFilter($product))) {
        $collection->addStoreFilter($this->getStoreFilter($product));
    }

    return $collection;
}

所以您可能想尝试这样做并看看它对您来说 return :

$collection = Mage::getResourceModel('catalog/product_type_configurable_product_collection')
    ->setFlag('require_stock_items', true)
    ->setFlag('product_children', true)
    ->load();

但是由于 Varien_Collection 的工作方式,如果您在两个可配置的产品中有相同的简单产品,您可能会遇到这样的错误:

Uncaught exception 'Exception' with message 'Item (Mage_Catalog_Model_Product) with the same id "some_id_here" already exist'

如果您遇到性能问题,最好使用直接 sql 查询,因为它占用的内存更少,而且速度更快。 像这样;

$coreResource = Mage::getSingleton('core/resource');
$connect = $coreResource->getConnection('core_write');

$prid = 12535;// Product entity id
$result = $connect->query("SELECT product_id FROM catalog_product_super_link WHERE parent_id=$prid");

while ($row = $result->fetch()):
        $sprid = $row['product_id'];
    // Now sprid contain the simple product id what is associated with that parent
    endwhile;

建议的 getUsedProductCollection() 是一个很好的起点。

原代码:

public function getUsedProductCollection($product = null)
{
    $collection = Mage::getResourceModel('catalog/product_type_configurable_product_collection')
        ->setFlag('require_stock_items', true)
        ->setFlag('product_children', true)
        ->setProductFilter($this->getProduct($product));
    if (!is_null($this->getStoreFilter($product))) {
        $collection->addStoreFilter($this->getStoreFilter($product));
    }

    return $collection;
}

您需要:

已复制并调整以查找多个可配置产品的二手产品:

$collection = Mage::getResourceModel('catalog/product_type_configurable_product_collection')
        ->setFlag('require_stock_items', true)
        ->setFlag('product_children', true);

$collection->getSelect()->where('link_table.parent_id in ?', $productIds);
$collection->getSelect()->group('e.entity_id');

$productIds 必须是一个包含所有可配置产品 ID 的数组。它是否也包含简单产品的 ID 并不重要。您可以改为构建 JOIN,但由于无论如何您都需要这些,我建议您首先加载原始集合,然后再加载使用过的关联产品。替代方案可能是使用 UNION 和 JOIN 的巨大查询,如果没有显着的性能提升就很难理解。

group('e.entity_id') 确保每个产品只被选中一次,以避免由于集合中的重复项而导致异常。