I have added location attribute for my products and wanted to filter my products by distance to a location using products geocode. The following code does not work for me.
$productCollection->addExpressionAttributeToSelect('distance',"( 3959 * acos( cos( radians('.$center_lat.') ) * cos( radians( latitude ) ) * cos( radians( longitude) - radians('.$center_lng.') ) + sin( radians('.$center_lat.') ) * sin( radians( latitude ) ) ) )", array('latitude'=>'latitude', 'longitude'=>'longitude'));
$productCollection->getSelect()->having('distance<=?',10)
->order('distance', Varien_Db_Select::SQL_ASC);
I tried using the two options there, neither worked. How to add dynamic field in magento collection
I finally solve the problem by join the eav/attribute_xxx table first. Here is the function to join the attribute.
protected function joinAttributeToSelect($select, $attrCode)
{
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attrCode);
$attrId = $attribute->getAttributeId();
$select->joinLeft(
array($attrCode => $attribute->getBackendTable()),
'(' . $attrCode . '.entity_id = e.entity_id) AND (' . $attrId . ' = ' . $attrCode . '.attribute_id)',
array($attrCode => $attrCode . '.value')
);
return $select;
}
After that, I can do where condition as I want. In my case the following code works.
$dist = sprintf(
"(%s*acos(cos(radians(%s))*cos(radians(latitude.value))*cos(radians(longitude.value)-radians(%s))+sin(radians(%s))*sin(radians(latitude.value))))",
3959,
(float)$center_lat,
(float)$center_lng,
(float)$center_lat
);
$productCollection->getSelect()->where($dist.'<=?', (float)$radius)
->order($dist,asc);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.