2013-02-15 92 views
1

我在我的应用程序中使用Yii和PostgreSQL和PostGIS。我有一个模型“用户”字段“位置”。位置字段的内容对于人类来说没有任何意义,但Postgres可以使用ST_asText方法转换位置字段的值并将其转换为经度和纬度。我在我的模型中创建了经度和纬度的虚拟域。当我保存模型时,我使用beforeSave和afterSave方法将位置设置为正确的值。Yii与PostGis,选择经度和纬度

我现在的问题是,我想经纬度虚拟字段填充模型创建(与数据库中的现有对象)。我在想,可能会有像beforeSelect和afterSelect这样的东西,我可以用一个额外的计算列追加查询,因此能够处理查询运行后从该额外列返回的值。

这是可能以某种方式?

回答

0

我能够解决这个很容易。我一直在寻找beforeFind和afterFind时,在CActiveRecord类中寻找beforeSelect和afterSelect方法。

下面是我做到这一点。欢迎任何改进建议:)

public function beforeFind(){ 
    $criteria = new CDbCriteria; 
    $criteria->select = "*,ST_asText(location) as location"; 
    $this->dbCriteria->mergeWith($criteria); 
    return parent::beforeFind(); 
} 

public function afterFind(){ 
    $location = str_replace('POINT(','',$this->location); 
    $location = str_replace(')','',$location); 
    $location = explode(" ", $location); 

    $this->lon = $location[0]; 
    $this->lat = $location[1]; 
    return parent::afterFind(); 
}