2

我尝试使用:按数量过滤集合: $_productCollection->addAttributeToFilter('qty', array('gt' => 30)); 但这不起作用。

有人可以给我一个提示,按数量过滤产品集合吗?

我也试过:

$stockCollection = Mage::getModel('cataloginventory/stock_item')->getCollection()
                             ->addFieldToFilter('qty', array('gt' => 99999999));
$entityIds = array();
foreach ($stockCollection as $item) {
    $entityIds[] = $item->getOrigData('product_id');
}

$_productCollection->addAttributeToFilter('id', array('in' => $entityIds));

entityId 数组为空,但 $_productCollection 仍然返回产品?!

4

1 回答 1

5

解释:

你在第二次尝试时很接近。有一种特殊的方法可以在Mage_CatalogInventory_Model_Resource_Stock_Item_Collection

/**
 * Add filter by quantity to collection
 *
 * @param string $comparsionMethod
 * @param float $qty
 * @return Mage_CatalogInventory_Model_Resource_Stock_Item_Collection
 */
public function addQtyFilter($comparsionMethod, $qty)
{
    $methods = array(
        '<'  => 'lt',
        '>'  => 'gt',
        '='  => 'eq',
        '<=' => 'lteq',
        '>=' => 'gteq',
        '<>' => 'neq'
    );
    if (!isset($methods[$comparsionMethod])) {
        Mage::throwException(
            Mage::helper('cataloginventory')->__('%s is not a correct comparsion method.', $comparsionMethod)
        );
    }

    return $this->addFieldToFilter('main_table.qty', array($methods[$comparsionMethod] => $qty));
}

解决方案:

$stockIds = Mage::getModel('cataloginventory/stock_item')
    ->getCollection()
    ->addQtyFilter('>=', 30)
    ->getAllIds();

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addIdFilter($stockIds)
    ->setPageSize(10);
于 2013-08-06T16:44:41.503 回答