我有一个从 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/