gpt4 book ai didi

mysql - 如何处理 Laravel 中的 mySql POINT 字段

转载 作者:行者123 更新时间:2023-12-01 10:06:20 30 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Laravel model with POINT/POLYGON etc. using DB::raw expressions

(3 个回答)


4年前关闭。




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

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

最佳答案

您目前拥有的只是数据库中的数据。 Schema::create刚刚在你的数据库中创建了表,然后你做了一个纯 SQL 插入语句。

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

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

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

这是一个改编的示例,根据您的情况,形成以下加载结果的帖子 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
在这里,您可以更精确地根据需要更改内容。

关于mysql - 如何处理 Laravel 中的 mySql POINT 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46615321/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com