我有一个 user_sessions 表,其中有一列名为“geo_location”,它是一个 POINT 列,用于存储用户当前位置的纬度和经度值,如果不可用,则为 NULL。
当我在 Laravel 中创建绑定(bind)到该表的模型时,它仅在 geo_location 字段完全隐藏时才有效。否则它会抛出 JSON 错误,因为它没有正确查询 geo_location 列中单独的 X 和 Y 值。
有没有一种方法可以在我的 Laravel 模型中创建一个访问器,该访问器可以在数据显示之前对其进行操作,以便我可以将其包含在我的结果中?
我是否需要修改我的 UserSessions Controller 并添加一个 get() 函数以仅使用原始 SQL?
最佳答案
如果您使用的是 PostGreSQL + PostGIS,这就是我为 L4.1 所做的
location 是 geometry(POINT) 类型,在迁移表中使用原始 sql 查询创建
表:
DB::statement("ALTER TABLE places ADD COLUMN location GEOMETRY(POINT, 4326)");
型号:
class Place extends Eloquent{
//mass assignment of fillable field
#fillable
protected $fillable = array('name', 'attribute', 'location');
// if you want to include your POINT data as a JSON attribute
#append
protected $append = array('location');
// the DB:raw statement is particular to PostGreSQL + PostGIS, a native function of PostGIS
// basically, find the id of the referred place
// and run the PostGIS function that turns the geometry type to wkt text.
#accessor
public function getLocationAttribute(){
$id = $this->attributes['id'];
$wkt = DB::table('places')->find( $id, array(DB::raw('ST_AsText(location) AS location')));
$location = $wkt->location;
return $location;
}
}
使用 REST 的示例输出如下所示:
{域}/地点/{1}
{
id: 1,
name: "Yellowstone",
created_at: "2014-05-19 08:19:51",
updated_at: "2014-05-19 08:19:51",
location: "POINT(121.1 14.4)"
}
注意:
使用默认访问器
$this->attributes['location']
返回一个十六进制对象,而不是一个字符串。所以我选择使用带有 PostGIS 函数的原始查询。
{
id: 1,
name: "Yellowstone",
created_at: "2014-05-19 08:19:51",
updated_at: "2014-05-19 08:19:51",
location: "0101000020E61000006666666666465E40CDCCCCCCCCCC2C40"
}
来自 WKT,我希望您可以使用 native php 脚本轻松返回经度/纬度。 :-)
我希望这能让您了解如何创建访问器。
关于php - 如何在 Laravel 4 模型中为 POINT 数据列创建访问器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23136898/