1

As an follow up idea to solve my "sort product collection by sub-category" problem explained in my question sorting collections by subcategory, an attribute and by productname I had the idea to add a AS expression to the selected fields of the collection.

What I want to achieve (SQL-wise) is something like this:

SELECT field1, 'some string' as 'category_name' FROM ...

So I thought I could use the addExpressionFieldToSelect in the method chain to dynamically add the category name string to the products collection.

For that have the following:

 // ...
 $_products = Mage::getModel('catalog/product')
     ->getCollection()
     ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
      ->addAttributeToSelect('*')
      ->addExpressionFieldToSelect('\'some category name\'', 'AS', 'category_name')
      ->addAttributeToFilter('status', 1)
      ->addAttributeToFilter('visibility', 4)
      ->addAttributeToFilter('is_saleable', array('like' => '1'))
      ->addAttributeToFilter('category_id', $_subcategory_finset_ids)
      ->addAttributeToSort('ws_geschmack', 'ASC')
      ->addAttributeToSort('name', 'ASC');
 // ...

But with that I get an error:

Fatal error: Call to undefined method Mage_Catalog_Model_Resource_Product_Collection::addExpressionFieldToSelect() ...

Short explanation: In fact I am not able to sort product collections by sub-category (string) I first query all child categories of a parent category (ordered) and within a loop I query all products of these child categories (down to the deepest level) to get products sublists of each subcategory and sub-sub categories. To fully understand my problem, please refer to my question mentioned above.

It is just a try, I do not know if all this is really working. As a hack for now I just try to come a little closer with that AS expression field holding the category name of the outer loop. I then could merge these collections and would have a final products collection.

If there is a more simple way, please let me know.

Any help is greatly appreciated!!

Update

Instead of using addExpressionFieldToSelect it is possible to use this:

 $_products->getSelect()
     ->columns(
         array(
            'category_name' => new Zend_Db_Expr(
                        'some string')
         )
     );
4

1 回答 1

3

如上所述,我在更新中使用以下方法解决了该问题:

$_products->getSelect()
    ->columns(
         array(
             'category_name' => new Zend_Db_Expr('some string')
         )
    );

其实很简单的解决方法!

于 2013-10-04T05:19:59.353 回答