【问题标题】:Eloquent returns POINT data as UTF8Eloquent 以 UTF8 格式返回 POINT 数据
【发布时间】:2017-02-01 21:25:24
【问题描述】:

我正在使用 Eloquent 从数据库中获取一些数据。我的数据库有一列使用 POINT 数据类型。这些列具有诸如POINT(52.45083 -1.930546) 之类的值。

我需要数据库中的这些数据,然后将其作为 JSON 返回。包括POINT 数据。但是,Eloquent 以以下形式返回它:

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

这是为什么?

【问题讨论】:

标签: php mysql laravel eloquent


【解决方案1】:

将以下代码添加到您的模型中。

protected $geofields = array('geo_coords');

然后为 geo_coords 添加 setter 和 getter

二传手

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

吸气剂

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

现在在查询时,您将值作为简单的字符串,包括 lat 和 long。

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

    return parent::newQuery($excludeDeleted)->addSelect('*',DB::raw($raw));
}

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 1970-01-01
    • 2011-06-11
    • 2017-02-24
    • 2015-07-22
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多