简体   繁体   English

如何通过表达多个属性来过滤magento产品集合

[英]How can I filter a magento product collection by expression of multiple attributes

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 如何在magento集合中添加动态字段

I finally solve the problem by join the eav/attribute_xxx table first. 我终于通过首先加入eav / attribute_xxx表解决了这个问题。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM