php - 如何在 Laravel 4 模型中为 POINT 数据列创建访问器?

标签 php mysql laravel geospatial point

我有一个 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/

相关文章:

php - Elasticsearch [查询 bool 值必须匹配]执行或运算,而不是与运算符

php - 如何让 PHP 正确地对数字索引数组进行 URL 编码?

php - 使用 PHP 在 SQL 中将 IP 地址存储为 0

mysql - 在时间范围后将 MySQL 记录移动到其他表

laravel - 图片有绝对路径 - 如何在 Laravel Mix 中使用子目录 URL

Laravel 4 动态数据库过滤器

php - 复合查询中的 mysqli_insert_id

php - 在 session Codeigniter 中访问数组

php - 将包含数据的新行添加到 ACF 中的现有转发器

mysql - Cognos 10.2.1 使用 JDBC 连接到 MySQL