【发布时间】:2013-07-30 10:38:11
【问题描述】:
我在 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的数据不正确。不知道为什么 - 有什么想法吗???
谢谢
【问题讨论】:
-
你的模特叫什么名字?
-
我不会使用
@ClassRegistry:调用(@ 在这里不好)。我也不会将太多特定的第三方 api 请求编码到模型的 beforeSave 方法中。尝试使用 lib 或行为来包装它。提示:dereuromark.de/2012/06/12/geocoding-with-cakephp -
模型名称为“Entry”
-
@mark 问题不在于检索到的数据不正确。问题是保存它!我是否必须格式化来自 GoogleAPI 的变量以使其适合小数 (13,9) 字段?
-
不正确是什么意思?你需要更具体。
标签: php database cakephp before-save