2013-02-12 63 views
1

我試圖使用計算haversine公式CakePHP中2.2.4距離時進行分頁結果的列表,但我發現周圍的錯誤在having子句中計算的字段。CakePHP的2.2.4不能使用分頁HAVING子句和計算領域的成果 - haversine公式

我認真地花了幾個星期試圖弄清楚這一點,但我不能。我讀過幾篇文章,有人說我需要重寫計數方法,有人說嘗試其他的東西,但與舊版本的Cake有關。

難道有人請告訴我究竟是我需要做些什麼才能使其工作?必須有數百人試圖實現同樣的目標並取得成功!

我正在使用的代碼是:

'Business' => array(
     'conditions' => array(
      'Business.is_active' => 1 
     ), 
     'fields' => array(
      'Business.*', 
      '(6371 * acos(cos(radians(' . $location['Location']['latitude'] . ')) * cos(radians(Business.latitude)) * cos(radians(Business.longitude) - radians(' . $location['Location']['longitude'] . ')) + sin(radians(' . $location['Location']['latitude'] . ')) * sin(radians(Business.latitude)))) AS distance' 
     ), 
     'group' => array(
      'Business.id HAVING distance <= 5', 
     ), 
     'contain' => array(
      'UserReview', 
      'Certification', 
      'Package' => array(
       'MassageType', 
       'PackageVariation' => array(
        'order' => array(
         'cost_in_dollars' => 'ASC' 
        ) 
       ) 
      ) 
     ), 
     'order' => array(
      'distance' => 'ASC', 
      'Business.name' => 'ASC', 
     ) 
    ) 

而且我不斷收到錯誤是:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'distance' in 'having clause'

請幫幫忙!

+1

爲什麼不使用虛擬這裏領域? – mark 2013-02-12 13:16:57

+0

你最好在mysql中使用存儲過程和存儲函數 – 2013-02-12 14:15:16

回答

0

我也試圖找到這個having子句問題的解決方案後,就放棄了。看來它在CakePHP V2中是不可能的。最後,我必須去用另一種方法:

$expression = '(3959 * acos(cos(radians(' . $session_lat . ')) * cos(radians(User.lat)) * cos(radians(User.lng) - radians(' . $session_lng . ')) + sin(radians(' . $session_lat . ')) * sin(radians(User.lat))))'; 
$conditions[] = $expression . ' < 100'; 
$this->controller->Paginator->settings = array(
    'fields' => array('Item.*', $expression.' as distance'), 
    'limit' => $limit, 
    'order' => array('Item.id' => 'Desc'), 
    'conditions' => $conditions, 
    'joins' => $joins, 
    'paramType' => 'querystring' 
); 

所以,你可以看到,我已經再度把計算的字段在狀態。我希望它能幫助別人。

0

這種情況的解決方案是使用虛擬領域:

$this->Business->virtualFields = array(
'distance' => '(6371 * acos(cos(radians(' . $location['Location']['latitude'] . ')) * cos(radians(Business.latitude)) * cos(radians(Business.longitude) - radians(' . $location['Location']['longitude'] . ')) + sin(radians(' . $location['Location']['latitude'] . ')) * sin(radians(Business.latitude))))' 
); 

後,您可以使用「距離」作爲一個字段:

$this->Paginator->settings = array(
    'limit' => 20, 
    'order' => array('Business.distance' => 'ASC'), 
    'conditions' => array('Business.distance <=' => 100) 
); 

$data = $this->Paginator->paginate('Business'); 

你可以閱讀更多關於CakePHP的虛擬域在這裏:http://book.cakephp.org/2.0/en/models/virtual-fields.html