【问题标题】:How to handle mySql POINT fields in Laravel [duplicate]如何在 Laravel 中处理 mySql POINT 字段 [重复]
【发布时间】:2018-03-18 19:49:05
【问题描述】:

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

 /**
 * 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 字段?

【问题讨论】:

  • 我没有。我直接保存在mySQL中
  • 这就是重点
  • 我将它导出为 SQL 语句,但它是 POINT(19.xxx -99.xxx)
  • 你知道我的坐标字段是什么吗?为什么我得到一个不可读的字段?

标签: mysql laravel geospatial laravel-5.5


【解决方案1】:

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

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

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

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

这是一个经过调整的示例,根据您的情况,形成以下帖子,从数据库加载结果 AsTextLaravel 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()-&gt;coordinates,结果将类似于POINT(19.4122475 -99.1731001)

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

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 2015-08-29
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 2018-02-04
    • 2016-06-02
    • 2021-05-20
    相关资源
    最近更新 更多