【问题标题】:How do I insert a mysql spatial point with a yii model?如何使用 yii 模型插入 mysql 空间点?
【发布时间】:2012-09-14 03:42:37
【问题描述】:

我有一个模型类型,它是从一个具有地址数据的 mysql 表和一个名为“坐标”的空间 POINT 字段生成的。创建或更新模型时,我想对地址进行地理编码并将纬度和经度坐标存储在 POINT 字段中。

我的理解是这样做的方法是在模型的beforeSave 方法中对地址进行地理编码。我已经这样做了,并且在关联数组中有坐标。现在我的问题是如何将这些数据插入到我的坐标字段中?这就是我正在尝试的:

public function beforeSave()
{
    $singleLineAddress = $this->getSingleLineAddress();
    $coords = Geocoder::getCoordinates($singleLineAddress);

    // WORKS: using the following line works to insert POINT(0 0)
    //$this->coordinates = new CDbExpression("GeomFromText('POINT(0 0)')");

    // DOESN'T WORK: using the following line gives an error
    $this->coordinates = new CDbExpression("GeomFromText('POINT(:lat :lng)')",
        array(':lat' => $coords['lat'], ':lng' => $coords['lng'] ));

    return parent::beforeSave();
}

当我这样做时,我收到以下错误:

CDbCommand 执行 SQL 语句失败:SQLSTATE[HY093]: 无效的参数号:绑定变量的数量不匹配 令牌的数量。执行的 SQL 语句是:INSERT INTO place (city, state, name, street, postal_code, phone, created, coordinates) 值 (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, UTC_TIMESTAMP(), GeomFromText('POINT(:lat :lng)'))

【问题讨论】:

    标签: mysql yii geospatial spatial


    【解决方案1】:

    如果您使用的是 Yii 2

    ,请在 @dlnGd0nG 的答案中进行小编辑
    $this->coordinates = new yii\db\Expression("GeomFromText(:point)",
        array(':point'=>'POINT('.$coords['lat'].' '.$coords['lng'].')'));
    

    【讨论】:

      【解决方案2】:

      试试这个

       $this->coordinates = new CDbExpression("GeomFromText(:point)",
              array(':point'=>'POINT('.$coords['lat'].' '.$coords['lng'].')'));
      

      【讨论】:

      • 对不起应该提到我也试过这个,它给出了同样的错误
      • 其实我错了,这行得通。我尝试了很多变化,我以为我已经尝试过了。
      猜你喜欢
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 2012-05-19
      • 1970-01-01
      • 2013-07-20
      相关资源
      最近更新 更多