2017-02-01 8 views
2

私はEloquentを使用してデータベースからデータを取得しています。私のデータベースには、POINTデータ型を使用する列があります。列の値はPOINT(52.45083 -1.930546)です。EloquentがPOINTデータをUTF8として返します

私はこのデータをデータベースから取得し、それをJSONとして返します。 POINTデータを含む。しかし、Eloquentは次の形式で返します。

array(7) { 
    ["id"]=> 
    int(2) 
    ["city_id"]=> 
    int(1) 
    ["image"]=> 
    NULL 
    ["name"]=> 
    string(20) "University of London" 
    ["geo_coords"]=> 
    string(25) "ͯ���[email protected]�h�^`V��" 
    ["created_at"]=> 
    string(19) "2017-01-11 10:53:46" 
    ["updated_at"]=> 
    NULL 
    } 

これはなぜですか?

+1

雄弁者がPOINTデータをサポートしているかどうかはわかりません。 https://laravel.com/docs/5.0/eloquent#accessors-and-mutatorsは、モデルを変換するうえで便利な方法です。 – apokryfos

+0

が役に立ちます:http://stackoverflow.com/questions/30682538/handling-mysql-spatial-datatypes-in-laravel-eloquent-orm – nogad

答えて

3

モデルに次のコードを追加します。

protected $geofields = array('geo_coords'); 

その後geo_coordsのためのセッターとゲッターに

セッター

public function setGeoCoordsAttribute($value) { 
    $this->attributes['geo_coords'] = DB::raw("POINT($value)"); 
} 

を追加ゲッター

public function getGeoCoordsAttribute($value) { 
    return str_replace(['POINT(', ')', ' '], ['', '', ','], $value); 
} 

照会ながら、あなたはワット、単純な文字列として値を指していますi緯度と経度。

public function newQuery($excludeDeleted = true) 
{ 
    $raw=''; 
    foreach($this->geofields as $column){ 
     $raw .= ' astext('.$column.') as '.$column.' '; 
    } 

    return parent::newQuery($excludeDeleted)->addSelect('*',DB::raw($raw)); 
} 
関連する問題