如何处理Laravel中的mySql POINT字段

时间:2017-10-06 23:50:07

标签: mysql laravel geospatial laravel-5.5

我正在创建一个这样的表:

 /**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{

    Schema::create('places', function (Blueprint $table) {
        $table->engine = 'MyISAM';

        $table->increments('id');
        $table->text('description');

        $table->longText('address');
        $table->point('coordinates');
        $table->timestamps();
    });
}

我使用以下方法直接在我的数据库中创建了一个字段:

INSERT INTO `places` (`id`, `description`, `address`, `coordinates`, `created_at`, `updated_at`)
VALUES
    (1, 'Plaza Condesa', 'Av. Juan Escutia 4, Hipodromo Condesa, Hipódromo, 06140 Cuauhtémoc, CDMX', X'000000000101000000965B5A0D89693340CC1B711214CB58C0', NULL, NULL);

然后我使用以下方法在Laravel中检索它:

MyModel::first()

所有值似乎都正确,除了coordinates字段,我得到这样的内容:

�[Z
�i3@�q�X�

如何使用Laravel获取POINT字段?

1 个答案:

答案 0 :(得分:3)

您目前所拥有的只是数据库中的数据。 Schema::create刚刚在数据库中创建了表,而不是在纯SQL插入语句中创建了表。

您没有存储字符串或整数,您使用了点数据类型
https://dev.mysql.com/doc/refman/5.7/en/gis-class-point.html

接下来你使用Laravel Eloquent获取这些数据,但从Eloquent的角度来看,你得到了一些二进制数据,如果你回复它,它看起来就像你发布的那样。

您需要的是模型类中的一些逻辑,它将二进制转换为您想要的格式。

这是一个改编的示例,根据您的情况,形成从DB加载结果AsText的以下帖子: Laravel model with POINT/POLYGON etc. using DB::raw expressions

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Places extends Model
{
    protected $geometry = ['coordinates'];

    /**
     * Select geometrical attributes as text from database.
     *
     * @var bool
     */
    protected $geometryAsText = true;

    /**
     * Get a new query builder for the model's table.
     * Manipulate in case we need to convert geometrical fields to text.
     *
     * @param  bool $excludeDeleted
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function newQuery($excludeDeleted = true)
    {
        if (!empty($this->geometry) && $this->geometryAsText === true)
        {
            $raw = '';
            foreach ($this->geometry as $column)
            {
                $raw .= 'AsText(`' . $this->table . '`.`' . $column . '`) as `' . $column . '`, ';
            }
            $raw = substr($raw, 0, -2);

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

        return parent::newQuery($excludeDeleted);
    }
}

现在你可以做到,例如echo Places::first()->coordinates,结果类似于POINT(19.4122475 -99.1731001)

根据您的要求,您还可以查看Eloquent Events。 https://laravel.com/docs/5.5/eloquent#events 在这里,您可以根据需要更精确地更改内容。