2017-10-06 88 views
1

我创建一个表是这样的:如何处理MYSQL POINT字段Laravel

/** 
* 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 
�[email protected]�q�X� 

如何使用Laravel获得POINT字段?

+0

我没有。我将它直接保存在mySQL中 – awavi

+0

这就是要点 – awavi

+0

我将它作为SQL语句导出,但它是POINT(19.xxx -99.xxx) – awavi

回答

1

你目前只有数据库中的数据。 Schema::create只是在你的数据库中创建了Table,而不是你创建了一个纯SQL插入语句。

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

接下来,您使用Laravel雄辩得到这个数据,但是从雄辩的时候,你得到了一些二进制数据,如果你回应它,它看起来像你发布。

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

这是一个适应例如,你的情况,形成以下后,从数据库加载结果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()->coordinates,结果将会是POINT(19.4122475 -99.1731001)

取决于你打算做什么你也可以看看雄辩事件。 https://laravel.com/docs/5.5/eloquent#events 在这里,您可以更精确地根据需要更改内容。