我正在尝试使用 MySQL 空间数据类型尽可能本地处理地图标记位置。我不想求助于额外的列,lat
最终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)
and的对象自动检索数据ST_Y(p)
?
这可能吗?