【问题标题】:Magento->filter product visibility in collectionMagento->过滤集合中的产品可见性
【发布时间】:2012-09-17 15:38:28
【问题描述】:

我们使用这个 Magento 代码来获取出版物列表,以便从中挑选 2 个以显示在书店部分。

$collection = Mage::getModel('catalog/category')->getCollection();
$collection->addAttributeToSelect('url_key')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('id')
    ->addAttributeToSelect('description')
    ->addAttributeToSelect('is_anchor')
    ->addAttributeToFilter('is_active', 1)
    ->joinUrlRewrite()
    ->load();

如何添加一个属性以使其不包括已设置的出版物 改为“不单独显示”?

如果我添加这个:

->addAttributeToFilter('visibility', 4) // Only catalog, search visiblity

代码失败并显示消息“无效的属性名称:可见性”

【问题讨论】:

    标签: magento-1.4


    【解决方案1】:

    可见性是产品属性,而不是类别属性。要获得只有可见度为 4 的 产品,您需要获得产品集合并遍历它以获得最终的类别列表:

    $categories = array();
    $products = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('visibility', 4);
    foreach($products as $product){ 
      foreach($product->getCategoryIds() as $cat){
         $categories[] = $cat;
      }
    }
    
    $categories = array_values(array_unique($categories));
    

    现在,$categories 数组填充了我们唯一的类别列表,我们只能加载这些类别:

    $cat = Mage::getModel('catalog/category')->getCollection()->addIdFilter($categories);
    

    【讨论】:

    • 类别集合中addIdFilter 的好处在于,您可以向其传递一个id 数组、逗号分隔的id 字符串,甚至是单数id 本身。它非常有用且灵活。
    • 如何从该类别中筛选出我已经在该系列中的产品?
    • 不要重新运行我设置 $products 的集合,而只需添加另一个条件。集合非常灵活——你可以先使用$collection->getFirst();,然后再使用$collection->addAttributeToFilter(array('id'=>3));,这样就可以了。实验一下。以上代码经过测试,运行良好。
    • 最好使用常量而不是硬编码的整数。例如:Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH
    • 更好的是,请查看Mage_Catalog_Model_Product_VisibilityMage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);.
    猜你喜欢
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多