我有一个名为“New”的类别,其中包含14个产品。
我正在使用Mage::getModel('catalog/category')->load(6);
加载此类别(6是管理员中的ID)。
如果我致电echo $category->getProductCount();
,它会正确显示14(此类别中的产品数量)。
现在,我正在使用
从类别中抓取产品$products = Mage::getModel('catalog/product')
->setStoreId( Mage::app()->getStore()->getId() )
->getCollection()
->addAttributeToFilter('visibility', $visibility)
->addCategoryFilter($category)
->addAttributeToSelect("*")
->setOrder('name','asc');
显示所有这14个产品,然后使用简单的foreach()
循环,但当我遍历$products
对象时,它实际上会返回我的所有产品。
我正在使用1.6.2.0版,我已经清除了缓存。
有没有人有理由不这样做?
修改
调用echo (string) $products->getSelect();
返回
SELECT `e`.*, IF(at_visibility.value_id > 0, at_visibility.value, at_visibility_default.value) AS `visibility`, `cat_index`.`position` AS `cat_index_position`, IF(at_name.value_id > 0, at_name.value, at_name_default.value) AS `name` FROM `catalog_product_entity` AS `e` INNER JOIN `catalog_product_entity_int` AS `at_visibility_default` ON (`at_visibility_default`.`entity_id` = `e`.`entity_id`) AND (`at_visibility_default`.`attribute_id` = '95') AND `at_visibility_default`.`store_id` = 0 LEFT JOIN `catalog_product_entity_int` AS `at_visibility` ON (`at_visibility`.`entity_id` = `e`.`entity_id`) AND (`at_visibility`.`attribute_id` = '95') AND (`at_visibility`.`store_id` = 1) INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id=1 AND cat_index.category_id='13' AND cat_index.is_parent=1 LEFT JOIN `catalog_product_entity_varchar` AS `at_name_default` ON (`at_name_default`.`entity_id` = `e`.`entity_id`) AND (`at_name_default`.`attribute_id` = '65') AND `at_name_default`.`store_id` = 0 LEFT JOIN `catalog_product_entity_varchar` AS `at_name` ON (`at_name`.`entity_id` = `e`.`entity_id`) AND (`at_name`.`attribute_id` = '65') AND (`at_name`.`store_id` = 1) WHERE (((IF(at_visibility.value_id > 0, at_visibility.value, at_visibility_default.value) = '4') OR (IF(at_visibility.value_id > 0, at_visibility.value, at_visibility_default.value) = '2'))) ORDER BY `name` as
答案 0 :(得分:5)
当简化为:
时,它适用于我$cat = Mage::getModel('catalog/product')->setId(198);
$products = Mage::getModel('catalog/product')
->getCollection()
->addCategoryFilter($cat)
->addAttributeToSelect("*")
->setOrder('name','asc')
->load();
foreach($products as $p) {
print_r($p->getSku().PHP_EOL);
}
顺便说一句,如果你在getCollection之后立即调用addAttributeToSelect,那么SQL对我来说更具可读性。