php Magento - 检索具有特定属性值的产品
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1332742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Magento - Retrieve products with a specific attribute value
提问by Christian
In my block code I am trying to programmatically retrieve a list of products that have a attribute with a specific value.
在我的块代码中,我试图以编程方式检索具有特定值属性的产品列表。
Alternately if that is not possible how would one retrieve all products then filter them to just list the products with a specific attribute?
或者,如果这是不可能的,如何检索所有产品然后过滤它们以仅列出具有特定属性的产品?
How would I perform a search using standard boolean filters ANDor ORto match a subset of my products?
我将如何使用标准布尔过滤器执行搜索AND或OR匹配我的产品子集?
回答by Alan Storm
Almost all Magento Models have a corresponding Collection object that can be used to fetch multiple instances of a Model.
几乎所有的 Magento 模型都有一个对应的 Collection 对象,可以用来获取一个模型的多个实例。
To instantiate a Product collection, do the following
要实例化产品集合,请执行以下操作
$collection = Mage::getModel('catalog/product')->getCollection();
Products are a Magento EAV style Model, so you'll need to add on any additional attributes that you want to return.
产品是 Magento EAV 样式模型,因此您需要添加要返回的任何其他属性。
$collection = Mage::getModel('catalog/product')->getCollection();
//fetch name and orig_price into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
There's multiple syntaxes for setting filters on collections. I always use the verbose one below, but you might want to inspect the Magento source for additional ways the filtering methods can be used.
有多种语法可用于在集合上设置过滤器。我总是使用下面的详细信息,但您可能需要检查 Magento 源以了解可以使用过滤方法的其他方式。
The following shows how to filter by a range of values (greater than AND less than)
下面显示了如何按值范围(大于和小于)过滤
$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'),
));
While this will filter by a name that equals one thing OR another.
虽然这将按等于一件事或另一件事的名称进行过滤。
$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'),
));
A full list of the supported short conditionals (eq,lt, etc.) can be found in the _getConditionSqlmethod in lib/Varien/Data/Collection/Db.php
支持的短条件(eq、lt 等)的完整列表可以在_getConditionSql方法中找到lib/Varien/Data/Collection/Db.php
Finally, all Magento collections may be iterated over (the base collection class implements on of the the iterator interfaces). This is how you'll grab your products once filters are set.
最后,所有 Magento 集合都可以迭代(基集合类实现了迭代器接口)。这就是设置过滤器后获取产品的方式。
$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());
}
回答by Christian
This is a follow up to my original question to help out others with the same problem. If you need to filter by an attribute, rather than manually looking up the id you can use the following code to retrieve all the id, value pairs for an attribute. The data is returned as an array with the attribute name as the key.
这是对我原来问题的跟进,以帮助其他有同样问题的人。如果您需要按属性过滤,而不是手动查找 id,您可以使用以下代码来检索属性的所有 id、值对。数据作为数组返回,以属性名称为键。
function getAttributeOptions($attributeName) {
$product = Mage::getModel('catalog/product');
$collection = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', $attributeName);
$_attribute = $collection->getFirstItem()->setEntity($product->getResource());
$attribute_options = $_attribute->getSource()->getAllOptions(false);
foreach($attribute_options as $val) {
$attrList[$val['label']] = $val['value'];
}
return $attrList;
}
Here is a function you can use to get products by their attribute set id. Retrieved using the previous function.
这是一个函数,您可以使用它们的属性集 ID 来获取产品。使用上一个函数检索。
function getProductsByAttributeSetId($attributeSetId) {
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('attribute_set_id',$attributeSetId);
$products->addAttributeToSelect('*');
$products->load();
foreach($products as $val) {
$productsArray[] = $val->getData();
}
return $productsArray;
}
回答by verheesj
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach($preparedManufacturers as $optionId => $value) {
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect('manufacturer');
$products->addFieldToFilter(array(
array('attribute'=>'manufacturer', 'eq'=> $optionId,
));
echo "<li>" . $value . " - (" . $optionId . ") - (Products: ".count($products).")</li>";
}
echo "</ul>";
}
回答by Pragnesh Karia
To Get TEXTattributes added from admin to front end on product listing page.
获取TEXT从管理员添加到产品列表页面前端的属性。
Thanks Anita Mourya
感谢安妮塔·穆里亚
I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.
我发现有两种方法。假设从后端添加名为“na_author”的产品属性作为文本字段。
METHOD 1
方法一
on list.phtml
在 list.phtml
<?php $i=0; foreach ($_productCollection as $_product): ?>
FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH
按 SKU 为每个产品加载并在 FOREACH 中获取属性
<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>
<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>
METHOD 2
方法二
Mage/Catalog/Block/Product/List.phtmlOVER RIDE and set in 'local folder'
Mage/Catalog/Block/Product/List.phtmlOVER RIDE 并设置在“本地文件夹”中
i.e. Copy From
即复制自
Mage/Catalog/Block/Product/List.phtml
and PASTE TO
并粘贴到
app/code/local/Mage/Catalog/Block/Product/List.phtml
change the function by adding 2 lines shown in bold below.
通过添加下面以粗体显示的 2 行来更改函数。
protected function _getProductCollection()
{
if (is_null($this->_productCollection)) {
$layer = Mage::getSingleton('catalog/layer');
/* @var $layer Mage_Catalog_Model_Layer */
if ($this->getShowRootCategory()) {
$this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
}
// if this is a product view page
if (Mage::registry('product')) {
// get collection of categories this product is associated with
$categories = Mage::registry('product')->getCategoryCollection()
->setPage(1, 1)
->load();
// if the product is associated with any category
if ($categories->count()) {
// show products from this category
$this->setCategoryId(current($categories->getIterator()));
}
}
$origCategory = null;
if ($this->getCategoryId()) {
$category = Mage::getModel('catalog/category')->load($this->getCategoryId());
if ($category->getId()) {
$origCategory = $layer->getCurrentCategory();
$layer->setCurrentCategory($category);
}
}
$this->_productCollection = $layer->getProductCollection();
$this->prepareSortableFieldsByCategory($layer->getCurrentCategory());
if ($origCategory) {
$layer->setCurrentCategory($origCategory);
}
}
**//CMI-PK added na_author to filter on product listing page//
$this->_productCollection->addAttributeToSelect('na_author');**
return $this->_productCollection;
}
and you will be happy to see it....!!
你会很高兴看到它....!!
回答by Pratik Kamani
create attribute name is "price_screen_tab_name". and access using this simple formula.
创建属性名称为“ price_screen_tab_name”。并使用这个简单的公式访问。
<?php $_product = $this->getProduct(); ?>
<?php echo $_product->getData('price_screen_tab_name');?>
回答by Anita Mourya
I have added line
我添加了行
$this->_productCollection->addAttributeToSelect('releasedate');
in
在
app/code/core/Mage/Catalog/Block/Product/List.php on line 95
app/code/core/Mage/Catalog/Block/Product/List.php 第 95 行
in function _getProductCollection()
在功能上 _getProductCollection()
and then call it in
然后调用它
app/design/frontend/default/hellopress/template/catalog/product/list.phtml
app/design/frontend/default/hellopress/template/catalog/product/list.phtml
By writing code
通过编写代码
<div><?php echo $this->__('Release Date: %s', $this->dateFormat($_product->getReleasedate())) ?>
</div>
Now it is working in Magento 1.4.x
现在它在 Magento 1.4.x 中工作

