我会尝试将addExpressionAttributeToSelect
添加到magento集合中。
当我尝试这一行时,它完美地运作:
// lat lng of Mallorca, Balearen, Spain
$lat = 39.695263;
$lng = 3.017571;
$dst = 250;
$mile2km = 1.609344;
echo "<pre>";
$col = Mage::getModel('catalog/product')->getCollection()->$this->addExpressionAttributeToSelect('latlngdistance', "ROUND(
DEGREES(
ACOS(
SIN(RADIANS( $lat )) * SIN(RADIANS( {{lat}} ))
+ COS(RADIANS( $lat )) * COS(RADIANS( {{lat}} ))
* COS(RADIANS( $lng - {{lng}} ))
) * 60 * 1.1515
) * $mile2km
, 1)", array('lat', 'lng'));
$this->getSelect()->having('latlngdistance <= ?', $dst);
$col->getSelect()->limit(10);
$col->load();
但是当我在一个Block中将这些方法添加到我的集合中时,Magento完全删除了我的addExpressionAttributeToSelect
错误结果:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'latlngdistance' in 'having clause'
(我在Block_Layer中添加了这个方法,方法:Mage_Catalog_Model_Layer :: prepareProductCollection)
编辑: 你必须编辑&#34; getSelectCountSql&#34;方法
EDIT2: 我在reirtirte-Collection课程中的最终解决方案(在My Modul中) 因此它适用于Flat和EAV Tables。所以我得到了正确数量的物品。
/**
* Get SQL for get record count
*
* @param bool $resetLeftJoins
* @return Varien_Db_Select
*/
protected function _getSelectCountSql($select = null, $resetLeftJoins = true)
{
$countSelect = parent::_getSelectCountSql($select, $resetLeftJoins);
if($this->getDirectCurPage() == 1)
{
$mile2km = $this->mile2km;
$lat = $this->lat;
$lng = $this->lng;
$_col_lat = 'e.lat';
$_col_lng = 'e.lng';
if(!$this->isEnabledFlat()) // if flat tables did work
{
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId())
->addFieldToFilter('attribute_code', array('in', array('lat', 'lng')));
$tables = array();
$attribute_ids = array();
foreach ($attributes as $attribute)
{
$attribute_ids[$attribute->getAttributeCode()] = $attribute->getId();
$tables[$attribute->getAttributeCode()] = $attribute->getBackendTable();
}
$_col_lat = 'pd_lat.value';
$_col_lng = 'pd_lng.value';
$countSelect->join(array('pd_lat' => $tables['lat']),
"e.entity_id = pd_lat.entity_id AND pd_lat.attribute_id = {$attribute_ids['lat']}", array());
$countSelect->join(array('pd_lng' => $tables['lng']),
"e.entity_id = pd_lng.entity_id AND pd_lng.attribute_id = {$attribute_ids['lng']}", array());
}
$countSelect->columns('COUNT(DISTINCT e.entity_id) as count');
$countSelect->columns(array('latlngdistance' => new Zend_Db_Expr("ROUND(
DEGREES(
ACOS(
SIN(RADIANS( $lat )) * SIN(RADIANS( {$_col_lat} ))
+ COS(RADIANS( $lat )) * COS(RADIANS( {$_col_lat} ))
* COS(RADIANS( $lng - {$_col_lng} ))
) * 60 * 1.1515
) * $mile2km
, 1)")));
$countSelect->group('latlngdistance');
$OldcountSelect = $countSelect;
$countSelect = $this->getConnection()->select();
$countSelect->from(array('a' => $OldcountSelect), array('SUM(a.count)'));
unset($OldcountSelect);
}
return $countSelect;
}