【问题标题】:CakePHP How to change Field in beforeSaveCakePHP 如何更改 beforeSave 中的字段
【发布时间】: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


【解决方案1】:

我们使用这个:

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

【讨论】:

  • 谢谢,但是这个“只”可以节省空间,但不能解决保存问题。
  • 验证是否可能失败? “不正确”是什么意思?
  • 没有验证工作,问题是如果我选择像不来梅(德国)这样的城市并保存条目,这个保存条目的数据库中的坐标是慕尼黑。这大约是 1000 公里的距离......如果我再次保存它,它会保存不来梅 - 我认为这是一个缓存问题,但我不知道这些值来自哪里
猜你喜欢
  • 2020-04-22
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多