2013-07-30 46 views
0

我在Cakephp中有一個模型,並且想要更改beforeSave函數中的字段,但保存的數據不正確。CakePHP如何更改beforeSave中的字段

這裏是我的功能:

public function beforeSave($options = array()) { 

    $address = @ClassRegistry::init('Address')->read(null, $this->data['Entry']['address_id']); 

     if($address != false) { 
      $url_address = $address['Address']['address']." ".$address['Address']['zip']." ".$address['Address']['city']; 
      $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.urlencode($url_address).'&sensor=false'); 
      $output = json_decode($geocode); 

      $lat = @$output->results[0]->geometry->location->lat; 
      $lng = @$output->results[0]->geometry->location->lng; 

      $this->data['Entry']['latitude'] = 0; 
     $this->data['Entry']['longitude'] = 0; 

     if($output->status == "OK") { 
      $this->data['Entry']['latitude'] = $lat; 
      $this->data['Entry']['longitude'] = $lng; 
     } 
    } 

    return true; 
} 

從GoogleAPI的結果是正確的我通過寫檢查的話:

print_r($this->data); 
exit(); 

只有寫在DB數據是不正確的。不知道爲什麼 - 任何想法?

THX

+0

你是什麼型號的名稱? –

+0

我不會使用@ClassRegistry:調用(這裏@是不好的)。我也不會將特定的第三方API請求過多地編入模型的beforeSave方法中。嘗試使用lib或行爲來包裝它。提示:http://www.dereuromark.de/2012/06/12/geocoding-with-cakephp/ – mark

+0

模型的名稱是「Entry」 –

回答

0

我們使用這樣的:

lat  decimal(10,8) 
lng  decimal(11,8) 
+0

謝謝,但是這個「only」 「節省空間,但不解決儲蓄問題。 –

+0

驗證失敗可能嗎? 「不正確」是什麼意思? – tersmitten

+0

沒有驗證工作,問題是,如果我選擇不來梅(德國)這樣的城市並保存條目,則保存條目的數據庫中的座標是慕尼黑。這是大約1000公里的距離...如果我再次保存它,它節省了不來梅 - 我認爲它是一個緩存問題,但我不知道值從何而來 –