Magento中的SQL Query集合

时间:2011-10-17 11:51:56

标签: mysql sql magento

我有这个问题:

        $collection = $this->getAssociatedProductCollection($product)
            ->addAttributeToSelect('*')
            ->addFilterByRequiredOptions()
            ->setPositionOrder()
            ->addStoreFilter($this->getStoreFilter($product))
            ->addAttributeToFilter('status', array('in' => $this->getStatusFilters($product)))
->addAttributeToSort('my_attribute', 'DESC');

我希望通过“my_attribute”

对相关产品进行订购

代码段->addAttributeToSort('my_attribute', 'DESC');没有给我带来好结果,因为我的数据存储在我的属性中。

我已经建立了一个测试数据库,并且我已经看到当前查询在我的测试数据库中做出了正确的顺序:

SELECT * FROM length ORDER BY my_attribute + 0

我的问题是:如何在我的第一个Magento查询中添加“+ 0”以通过以下方式做出正确的顺序:)

[编辑]

这是我完整的修改功能:

public function getAssociatedProducts($product = null)
{
    if (!$this->getProduct($product)->hasData($this->_keyAssociatedProducts)) {
        $associatedProducts = array();

        if (!Mage::app()->getStore()->isAdmin()) {
            $this->setSaleableStatus($product);
        }


        $collection = $this->getAssociatedProductCollection($product)
            ->addAttributeToSelect('*')
            ->addFilterByRequiredOptions()
            ->setPositionOrder()
            ->addStoreFilter($this->getStoreFilter($product))
            ->addAttributeToFilter('status', array('in' => $this->getStatusFilters($product)))
            ->addAttributeToSort('breite', 'ASC')
            // My Modification 
            ->addAttributeToSort('my_attribute', 'ASC');
            // My Modification 


        foreach ($collection as $item) {
            $associatedProducts[] = $item;
        }

        $this->getProduct($product)->setData($this->_keyAssociatedProducts, $associatedProducts);
    }
    return $this->getProduct($product)->getData($this->_keyAssociatedProducts);
}

[/ EDIT]

非常感谢。 :)

1 个答案:

答案 0 :(得分:1)

没有简单的方法可以做到这一点,我建议你确切地检查你的收藏品是做什么的:

vardump((string)$collection->getSelect());

那应该返回用于检索该集合的查询,然后您可以在代码中使用直接SQL。

其他选项是使用PHP数组排序函数对集合进行排序,如:

$data = $collection->getItems();  //an array of objects-
usort($data,array('my_attribute','sortByMyAttribute'));
return $data;

function sortByMyAttribute(){
   #
   # Do your desired sort here
}

看到更新代码后确定:

   $collection = $this->getAssociatedProductCollection($product)
        ->addAttributeToSelect('*')
        ->addFilterByRequiredOptions()
        ->addStoreFilter($this->getStoreFilter($product))
        ->addAttributeToFilter('status', array('in' => $this->getStatusFilters($product)))
        ->addAttributeToSort('breite', 'ASC')

我删除了set positionOrder,让我知道它是怎么回事