2012-02-03 2 views
5

제품 컬렉션을 필터링하고 페이지 매김을 지정하려고합니다. 모든 것이 괜찮습니다 - 페이지 매김을 제외하고. 메신저는 첫 번째 페이지에 대해 3 개의 항목 대신 전체 컬렉션을 다시 가져옵니다.Magento : 필터링 된 제품 모음 페이지 넘김

//fetch all visible products 
    $product_collection = Mage::getModel('catalog/product')->getCollection(); 

    //set wanted fields (nescessary for filter) 
    $product_collection->addAttributeToSelect('name'); 
    $product_collection->addAttributeToSelect('description'); 
    $product_collection->addAttributeToSelect('price'); 
    $product_collection->addAttributeToFilter('visibility', array('neq' => 1)); 

    //filter by name or description 
    $product_collection->addFieldToFilter(array(
      array('attribute'=>'name','like'=>$sTerm), 
      array('attribute'=>'description','like'=>$sTerm) 
    )); 

    //filter for max price 
    foreach ($product_collection as $key => $item) { 
     if($item->getPrice() >= $priceTo){ 
      $product_collection->removeItemByKey($key); 
     } 
    } 

    //pagination (THIS DOESNT WORK!) 
    $product_collection->setPageSize(3)->setCurPage(1); 

    //TEST OUTPUT 
    foreach ($product_collection as $product) { 
      echo $product->getName().'<br />'; 
    } 

감사합니다.

답변

4

감사합니다. @Ben! 너는 내게 올바른 힌트를 주었다. 이제 효과가 있습니다! 기본적으로 다른 컬렉션을 만들고 이미 필터링 된 항목의 ID로이 컬렉션을 필터링합니다. 이후에 새 컬렉션에 페이지 매김을 쉽게 추가 할 수 있습니다. 작동 코드 :

//fetch all visible products 
    $product_collection = Mage::getModel('catalog/product')->getCollection(); 

    //set wanted fields (nescessary for filter) 
    $product_collection->addAttributeToSelect('name'); 
    $product_collection->addAttributeToSelect('description'); 
    $product_collection->addAttributeToSelect('price'); 
    $product_collection->addAttributeToFilter('visibility', array('neq' => 1)); 

    //filter by name or description 
    $product_collection->addFieldToFilter(array(
      array('attribute'=>'name','like'=>$sTerm), 
      array('attribute'=>'description','like'=>$sTerm) 
    )); 

    //filter for max price 
    foreach ($product_collection as $key => $item) { 
     if($item->getPrice() >= $priceTo){ 
      $product_collection->removeItemByKey($key); 
     } 
    } 

    //build id array out of filtered items (NEW!) 
    foreach($product_collection as $item){ 
     $arrProductIds[]=$item->getId(); 
    } 

    //recreate collection out of product ids (NEW) 
    $product_filtered_collection = Mage::getModel('catalog/product')->getCollection(); 
    $product_filtered_collection->addAttributeToFilter('entity_id', array('in'=>$arrProductIds)); 


    //add pagination (on new collection) (NEW) 
    $product_filtered_collection->setPageSize(3)->setCurPage(1); 


    //TEST OUTPUT 
    foreach ($product_filtered_collection as $product) { 
      echo $product->getName().'<br />'; 
    } 
13

너무 가까이 있습니다! $product_collection->setPageSize(3)->setCurPage(1);전에 전에 컬렉션을 통해 첫 번째 foreach() 반복을 시도해보십시오.

Magento 컬렉션은 지연로드됩니다. 직접 load() (또는 count() 또는 foreach())을 통해 암시 적으로로드 할 때까지 기본 쿼리 (EDIT : 아래 참고 참조)에 영향을주는 컬렉션 속성을 수정할 수 있습니다. 컬렉션이 명시 적으로 또는 암시 적으로로드 된 후에는 _items 속성의 멤버 만 가져옵니다.

FYI 원래의 쿼리에 영향을 미치는 속성 (필터, 분류기, 제한, 조인 등)을 그대로두고 추가 속성을 추가하려면 clear()으로 전화 할 수 있습니다.

HTH

편집 : 사실, 질의 특성을 조정하는 관계없이 _items 부하 상태를 항상 가능하지만 컬렉션이 재생 될 때까지 효과가 표시되지 않습니다.

+0

지금까지 감사합니다! 컬렉션을 다시 생성하려고했습니다 : '$ product_filtered_collection = new Varien_Data_Collection(); foreach ($ product_collection $ item) { $ product_filtered_collection-> addItem ($ item); } '...이 새 컬렉션에 페이지 매김을 추가했습니다. 하지만 그 중 하나가 작동하지 않습니다. –

+0

어. 나는 방금 당신의 게시물을 다시 읽었습니다. 해결할 두 가지 큰 문제가 있습니다. 콜렉션을 페이지 매기기 (paraginate)하기 위해서는 데이터를로드하기 위해 원래의 쿼리에 가격 필터링을 포함시켜야합니다 (foreach()가 데이터를 먼저로드하므로 그렇지 않습니다) 또한 최종 가격 로직 Magento는이 컬렉션의 항목에 대해 실행되지 않는 옵저버의 영향을받을 수 있습니다. 죄송합니다. – benmarks

+0

예 @ 벤! 올바른 방향으로 나를 가리켰습니까. 이제 작동합니다. 약 4 시간 후 작업 예제를 게시합니다. 내 신용도가 너무 낮습니다.) 기본적으로 새 컬렉션을 만들고 항목의 제품 ID로 필터링 한 다음 나중에 페이지 매김합니다. –

관련 문제