2017-10-06 85 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 在這裏,您可以更精確地根據需要更改內容。