[英]Overriding Laravel Model View
我正在尝试使用MySQL空间数据类型尽可能本机处理地图标记位置。 我不想求助于lat
和lng,
其他列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.