mysql - 如何使用 yii 模型插入 mysql 空间点?

标签 mysql yii geospatial spatial

我有一个从 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 failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: INSERT INTO place (city, state, name, street, postal_code, phone, created, coordinates) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, UTC_TIMESTAMP(), GeomFromText('POINT(:lat :lng)'))

最佳答案

如果您使用的是 Yii 2,请对 @dlnGd0nG 的回答进行小幅修改

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

关于mysql - 如何使用 yii 模型插入 mysql 空间点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12535245/

相关文章:

mysql - 更好的 hibernatre 数据库设计?

mysql防止插入行自动排序

php - 从外键表中检索字段

php - Yii2:无法通过 + 1 更新列值

php - 伊伊 : Error in defining an array

php - 是否需要验证 $_GET id

php - Yii - 在 GridView 单元格内渲染小部件

node.js - 如何通过nodejs使用Apache Ignite空间功能?

c# - 转换 EPSG :4326 projection to EPSG:3857 mercator

r - 如何根据 R 中的时间矩阵对点进行排序?