我已经疯狂地在谷歌上搜索,试图找到一个真正有效的解决方案来解决这个问题,但是都没有结果。
在分类页面使用“按函数排序”功能按属性(容量、重量等)对产品进行排序时,Magento会以文本字符串的形式进行排序,因为它认为数字是文本字符串:
产品A: 10kg
产品B: 11kg
产品C: 15kg
产品D: 9kg
而实际上应该这样排序:
产品D: 9kg
产品A: 10kg
产品B: 11kg
产品C: 15kg
查看了一些资料后,人们建议将想要按数字排序的属性在eav_attribute表中的backend_type更改为小数并将frontend_input更改为价格。然而,这不仅似乎无法真正起作用,而且它会改变数字的格式,在其前面加上美元符号($),因为我们在产品页面上显示实际属性值,并且还要通过它进行排序,所以它并不能解决问题。
我正在尝试弄清楚getSortOrder()方法的确切作用,但是看起来这种功能被嵌入得非常深,所以我很难想出解决这个错误的方法。
任何帮助都将不胜感激!
编辑:
对于未来想要解决此问题的任何人,这是我想出的解决方法:
您需要覆盖存储在app/Code/Mage/core/catalog/block/product/list.php中的List.php中的_getProductCollection()函数。
将该文件复制到app/code/Mage/local/catalog/block/product/list.php中,以避免编辑核心文件。
然后,在下面它说的位置:
$this->_productCollection = $layer->getProductCollection();
请放置以下代码:
// Start of Code to force Magento to numerically sort decimal attributes rather than alphabetically
$filterAttribute = $this->getRequest()->getParam('order');
$filterAttributeDir = $this->getRequest()->getParam('dir');
$attributeType = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', $filterAttribute)->getFrontendClass();
// If a Sort By option is selected on category page and attribute has frontend_class = validate-number or validate-digits
// then CAST the attribute values as signed integers
if (isset($filterAttribute) && ($attributeType == 'validate-digits' || $attributeType == 'validate-number')) {
$this->_productCollection->getSelect()->reset(Zend_Db_Select::ORDER);
$this->_productCollection->getSelect()->order('CAST(`' . $filterAttribute . '` AS SIGNED) ' . $filterAttributeDir . "'");
}
// End of code to force Magento to numerically sort....
如果您在管理员面板中为属性设置为十进制数或整数数的商店所有者进行输入验证,则此代码将重置产品集合上的排序顺序,然后将其转换为有符号整数,以使其按数值而不是按字母表顺序排序。
希望对某些人有所帮助!