1

私は自分のアプリケーションでPostgreSQLとPostGISと一緒にYiiを使用しています。「場所」フィールドを持つモデル「ユーザー」があります。Location-fieldの内容は人間にはまったく意味がありませんが、PostgresはLocation-fieldの値を変換し、ST_asTextメソッドを使用して経度と緯度に変換できます。モデルに経度と緯度のダミーフィールドを作成しました。モデルを保存するときは、beforeSaveメソッドとafterSaveメソッドを使用して、場所を正しい値に設定します。

私の問題は、モデルの作成時に緯度と経度のダミーフィールドにデータを入力することです(データベース内の既存のオブジェクトを使用)。beforeSelectやafterSelectのように、追加の計算列をクエリに追加するために使用できるものがあるのではないかと考えていたため、クエリの実行後にその追加の列から返された値を処理できます。

これはどういうわけか可能ですか?

4

2 に答える 2

1

私はこれをかなり簡単に解決することができました。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();
}
于 2013-02-15T17:12:10.310 に答える
0

私はYii2でこの問題に遭遇しました、そしてこれが私がそれを解決した方法です。

  1. find()ARのメソッドをオーバーライドし、独自のActiveQueryクラスを定義します。

    public static function find()
    {
        $query =  new MyActiveQueryClass(get_called_class());
        return $query->select('*, ST_AsGeoJSON(location) AS location');
    }
    
  2. afterFind()あなたはgeo-jsonを持っているでしょう、そしてそれであなたはlat /lngを得ることができます:

    public function afterFind()
    {
        parent::afterFind();
    
        $geoJson = json_decode($this->location, true);
        $this->lat = $geoJson['coordinates'][0];
        $this->lng = $geoJson['coordinates'][1];
    }
    

Yii2は以上です。保存する前に、lat/lngを正しいオブジェクトに変換することを忘れないでください。私のは地理のコラムでした。ここにボーナスがあります:

public function beforeSave($insert)
{
    //create field as expression
    if(!empty($this->lat) && !empty($this->lng))
        $this->location = new \yii\db\Expression("'POINT({$this->lat} {$this->lng})'");

    return parent::beforeSave($insert);
}
于 2018-09-15T10:49:24.950 に答える