2009-08-26 41 views
76

Trong mã khối của tôi, tôi đang cố truy xuất một danh sách các sản phẩm có thuộc tính với một giá trị cụ thể.Magento - Lấy các sản phẩm có giá trị thuộc tính cụ thể

Cách khác là không thể làm thế nào để truy xuất tất cả các sản phẩm sau đó lọc chúng để chỉ liệt kê các sản phẩm có thuộc tính cụ thể?

Tôi làm cách nào để thực hiện tìm kiếm bằng bộ lọc boolean chuẩn AND hoặc OR để khớp với một tập hợp con các sản phẩm của tôi?

Trả lời

160

Hầu như tất cả các Mô hình Magento đều có đối tượng Bộ sưu tập tương ứng có thể được sử dụng để tìm nạp nhiều phiên bản của Mô hình.

Để tạo một bộ sưu tập sản phẩm, làm như sau

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

Sản phẩm được một phong cách mẫu Magento EAV, vì vậy bạn sẽ cần phải thêm vào bất kỳ thuộc tính bổ sung mà bạn muốn quay trở lại.

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

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

Có nhiều cú pháp để đặt bộ lọc trên bộ sưu tập. Tôi luôn luôn sử dụng một trong những tiết dưới đây, nhưng bạn có thể muốn kiểm tra nguồn Magento cho những cách bổ sung các phương pháp lọc có thể được sử dụng.

Sau đây cho thấy làm thế nào để lọc theo một loạt các giá trị (lớn hơn và ít hơn)

$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'), 
)); 

Trong khi điều này sẽ lọc theo một cái tên đó bằng một điều này hay cách khác.

$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'),   
)); 

Một danh sách đầy đủ các điều kiện ngắn được hỗ trợ (eq, lt, vv) có thể được tìm thấy trong các phương pháp _getConditionSql trong lib/Varien/Data/Collection/Db.php

Cuối cùng, tất cả các bộ sưu tập Magento có thể được lặp trên (lớp bộ sưu tập cơ sở thực hiện trên các giao diện trình lặp). Đây là cách bạn sẽ lấy sản phẩm của mình khi bộ lọc được đặt.

$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('name'=>'orig_price','eq'=>'Widget A'), 
    array('name'=>'orig_price','eq'=>'Widget B'),  
)); 

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

câu trả lời rất chi tiết. cảm ơn! –

+0

Cảm ơn bạn rất nhiều vì câu trả lời chi tiết. Bạn đã đặt tôi dọc theo con đường bên phải. Tôi đã thực hiện một var_dump kết quả từ mã ví dụ của bạn. Bởi vì thuộc tính tôi đang làm việc với một mục chọn nhiều, tôi nhận được một số id trong các kết quả nên so sánh văn bản không hoạt động. VÍ DỤ.$ this-> collection-> addFieldToFilter (mảng ( mảng ('thuộc tính' => 'cw_category', 'eq' => 'Aero'), mảng ('thuộc tính' => 'cw_category', 'eq' => 'Theo dõi'), mảng ('thuộc tính' => 'cw_category', 'eq' => 'Tham quan') )); Đang trả lại 'cw_category' => string ', 536,535,534' (length = 12) – Christian

+0

Không thể giúp bạn một cách cụ thể mà không cần đào nhiều (StackOverflow rep là tốt, nhưng không thanh toán hóa đơn). Hai con đường để bạn theo đuổi. Đầu tiên, như đã đề cập, checkout _getConditionSql cho một danh sách tất cả các toán tử so sánh có thể. Thứ hai, nếu bạn kiểm tra PHPDoc cho phương thức addAttributeToFilter trên Mage_Eav_Model_Entity_Collection_Abstract, bạn sẽ thấy rằng một trong các giá trị kỳ vọng của tham số đầu tiên là một Mage_Eav_Model_Entity_Attribute_Interface. Điều đó có thể dẫn bạn vào con đường chính xác. –

7

Đây là câu hỏi ban đầu của tôi để giúp những người khác có cùng vấn đề. Nếu bạn cần lọc theo thuộc tính, thay vì tìm kiếm id theo cách thủ công, bạn có thể sử dụng mã sau để truy xuất tất cả các cặp id, giá trị cho một thuộc tính. Dữ liệu được trả về dưới dạng một mảng với tên thuộc tính làm khóa.

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; 
} 

Đây là chức năng bạn có thể sử dụng để lấy sản phẩm theo id thuộc tính. Lấy bằng cách sử dụng chức năng trước đó.

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; 
} 
0

tôi đã thêm dòng

$this->_productCollection->addAttributeToSelect('releasedate'); 

trong

app/code/core/Mage/Catalogue/Khối/sản phẩm/danh sách.php on line 95

chức năng _getProductCollection()

và sau đó gọi nó trong

ứng dụng/thiết kế/frontend/default/hellopress/template/Danh mục hàng/sản phẩm/list.phtml

Bằng cách viết mã

<div><?php echo $this->__('Release Date: %s', $this->dateFormat($_product->getReleasedate())) ?> 
</div> 

Hiện tại, nó đang hoạt động trong Magento 1.4.x

3

Để nhận được TEXT các thuộc tính được thêm từ quản trị viên vào giao diện người dùng trên trang danh sách sản phẩm.

Cảm ơn Anita Mourya

Tôi đã tìm thấy có hai phương pháp. Giả sử thuộc tính sản phẩm được gọi là "na_author" được thêm từ chương trình phụ trợ dưới dạng trường văn bản.

PHƯƠNG PHÁP 1

trên list.phtml

<?php $i=0; foreach ($_productCollection as $_product): ?> 

CHO MỖI TẢI sản phẩm bằng cách SKU VÀ GET thuộc tính bên trong 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 "";} 
?> 

PHƯƠNG PHÁP 2

Mage/Catalog/Block/Product/List.phtml VỀ RIDE và thiết lập trong ' thư mục cục bộ '

ví dụ: Copy From

Mage/Catalog/Block/Product/List.phtml 

và dán vào

app/code/local/Mage/Catalog/Block/Product/List.phtml 

thay đổi chức năng bằng cách thêm 2 dòng được in đậm dưới đây.

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; 

} 

và bạn sẽ rất vui khi thấy nó .... !!

5
$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>"; 
} 
2

tạo tên thuộc tính là "price_screen_tab_name". và truy cập bằng công thức đơn giản này.

<?php $_product = $this->getProduct(); ?> 
<?php echo $_product->getData('price_screen_tab_name');?> 
Các vấn đề liên quan