我有一个从具有地址数据的mysql表生成的模型类型,以及一个名为“coordinates”的空间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
)VALUES(:yp0,:yp1,:yp2,:yp3,:yp4,:yp5, UTC_TIMESTAMP(),GeomFromText('POINT(:lat:lng)'))
答案 0 :(得分:3)
试试这个
$this->coordinates = new CDbExpression("GeomFromText(:point)",
array(':point'=>'POINT('.$coords['lat'].' '.$coords['lng'].')'));
答案 1 :(得分:3)
如果您使用 Yii 2
,请在@ dlnGd0nG的答案中进行小编辑$this->coordinates = new yii\db\Expression("GeomFromText(:point)",
array(':point'=>'POINT('.$coords['lat'].' '.$coords['lng'].')'));