【问题标题】:Add AS-Expression to selected columns in getCollection()将 AS-Expression 添加到 getCollection() 中的选定列
【发布时间】:2013-10-02 05:09:24
【问题描述】:

作为解决我的问题sorting collections by subcategory, an attribute and by productname 中解释的“按子类别对产品集合进行排序”问题的后续想法,我想到了将AS 表达式添加到集合的选定字段中。

我想要实现的(SQL 方式)是这样的:

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

所以我想我可以使用方法链中的addExpressionFieldToSelect 将类别名称字符串动态添加到产品集合中。

为此有以下几点:

 // ...
 $_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');
 // ...

但是我得到一个错误:

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

简短说明:实际上我无法按子类别(字符串)对产品集合进行排序我首先查询父类别的所有子类别(有序),然后在循环中查询这些子类别的所有产品(向下到最深的层次)获取每个子类别和子子类别的产品子列表。要完全理解我的问题,请参考我上面提到的问题。

这只是一个尝试,我不知道这一切是否真的有效。作为一个 hack,我现在只是尝试更接近 AS expression 字段,该字段包含外部循环的类别名称。然后我可以合并这些集合,并拥有一个最终产品集合。

如果有更简单的方法,请告诉我。

非常感谢任何帮助!

更新

可以使用这个来代替addExpressionFieldToSelect:

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

【问题讨论】:

  • 如果更新解决了您的问题,请将其作为答案并接受它。

标签: sql magento zend-framework collections


【解决方案1】:

正如我在更新中所述,我通过以下方式解决了问题:

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

其实很简单的解决方案!

【讨论】:

    猜你喜欢
    • 2013-03-30
    • 2015-04-30
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多