php - Magento - 检索具有特定属性值的产品

标签 php magento e-commerce entity-attribute-value

在我的 block 代码中,我试图以编程方式检索具有特定值属性的产品列表。

如果不可能的话,如何检索所有产品然后过滤它们以仅列出具有特定属性的产品?

如何使用标准 bool 过滤器 ANDOR 执行搜索以匹配我的产品子集?

最佳答案

几乎所有 Magento 模型都有一个对应的 Collection 对象,可用于获取模型的多个实例。

要实例化产品集合,请执行以下操作

$collection = Mage::getModel('catalog/product')->getCollection();

产品是 Magento EAV 样式的模型,因此您需要添加要返回的任何其他属性。

$collection = Mage::getModel('catalog/product')->getCollection();

//fetch name and orig_price into data
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

有多种语法可用于在集合上设置过滤器。我总是使用下面的详细方法,但您可能需要检查 Magento 源代码以了解可以使用过滤方法的其他方式。

下面展示了如何通过值范围(大于和小于)进行过滤

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
    array('attribute'=>'orig_price','gt'=>'100'),
)); 

//AND filter for products whose orig_price is less than (lt) 130
$collection->addFieldToFilter(array(
    array('attribute'=>'orig_price','lt'=>'130'),
));

虽然这将按等于一件事或另一件事的名称进行过滤。

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
    array('attribute'=>'name','eq'=>'Widget A'),
    array('attribute'=>'name','eq'=>'Widget B'),        
));

可在 lib/Varien/Data/Collection/Db.php 中的 _getConditionSql 方法中找到支持的短条件(eq、lt 等)的完整列表

最后,所有 Magento 集合都可以迭代(基集合类实现了迭代器接口(interface))。这就是您在设置过滤器后获取产品的方式。

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('orig_price');    

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
    array('attribute'=>'name','eq'=>'Widget A'),
    array('attribute'=>'name','eq'=>'Widget B'),        
));

foreach ($collection as $product) {
    //var_dump($product);
    var_dump($product->getData());
}

关于php - Magento - 检索具有特定属性值的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1332742/

相关文章:

php - 将 .JSON 导入 MySQL

用于从 Magento 中的 sitemap.xml 中排除特定类别页面的 PHP 代码

sql - 电子商务网站上非注册用户的订单存储在哪里?

android - Google Analytics 不显示购买但显示事件

testing - 需要一些关于安全测试的信息

php - 选择左连接,除了一列

javascript - 如何自动关闭我的警报

php - onPostExecute 永远不会被调用,但 doInBackground 返回值

mysql - 在magento中批量替换产品标题

magento - 如何根据特价供应情况加载特定类别的产品?