簡體   English   中英

覆蓋Laravel模型視圖

[英]Overriding Laravel Model View

我正在嘗試使用MySQL空間數據類型盡可能本機處理地圖標記位置。 我不想求助於latlng,其他列lng,因為最終,我也希望能夠編碼線和面(以及其他幾何形狀)。 該表具有point列類型:

Schema::create('maps', function (Blueprint $table) {
    $table->increments('id');
    $table->point('map_center')->nullable();
    $table->timestamps();
});

在視圖方面,由於內置支持在數據庫中創建這些空間類型,因此Eloquent比我想象的要笨拙。 如果我get()模型,則map_center顯示原始編碼的幾何。

>>> $map=Map::first()
=> App\Map {#2935
     id: 1,
     map_center: b"\0\0\0\0\x01\x01\0\0\0ºõš\x1E\x14\x7FRÀb0\x7F…Ì_D@",
     created_at: null,
     updated_at: null,
   }

我編寫了一個center()方法,該方法返回包含lat和long的對象:

public function center()
{
    if ($this->map_center) 
    {
        $result = DB::select('
            select ST_Y(map_center) as lat, ST_X(map_center) as lng 
            from maps 
            where id = :id
        ', 
        ['id' => $this->id]);
        $center['lat'] = $result[0]->lat;
        $center['lng'] = $result[0]->lng;
        return (object) $center;
    }
    else
    {
        dd($this);
    }
} 

輸出:

>>> $map->center()->lat
=> 40.748429

這是一個不錯的解決方法,但是有點難看。 相反,我希望Eloquent提取該內容,以便模型返回人類可讀的坐標,例如:

>>> $map=Map::first()
=> App\Map {#2935
     id: 1,
     map_center: {
       lat: 40.748429,   // or X: and Y:
       lng: -73.985603, 
     }
     created_at: null,
     updated_at: null,
   }

鑒於它是point類型(具有兩個組件),是否可以使用ST_AsText(p)或包含ST_X(p)ST_Y(p)的對象自動檢索數據?

這可能嗎?

MySQL將數據存儲為WKB(眾所周知的二進制)格式。

在這里看看如何在PHP中轉換MySQL二進制GEOMETRY字段

您可以使用模型屬性 應該是這樣的。

public function getMapCenterAttribute()
{
    $center = unpack('Lpadding/corder/Lgtype/dlatitude/dlongitude', $this->map_center);
    return $center;
}

你也應該有類似的東西, setMapCenterAttribute用做反pack ,如果需要的功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM