postgresql - 我如何在 typeorm 和 postgres 中使用经度和纬度
问题描述
我当前的实体如下所示:
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Landmark extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
longitude: number
@Column()
latitude: number
}
但我想知道是否有更好的方法来做到这一点,使用特殊的 postgres 类型,它适用于 typeorm。
解决方案
您将要查看 Typeorm 中的 PostGIS 和 Spatial Column 支持:
https://github.com/typeorm/typeorm/blob/master/docs/entities.md#spatial-columns
PostGIS 是一个扩展,您可以在 postgres 数据库中启用以处理空间数据类型。安装 PostGIS 后,您可以在 Typeorm 查询构建器中使用其特殊的空间数据函数,就像使用由 GeoJSON 支持的任何其他 PG 函数一样。
Typeorm 的 postgres 驱动程序在内部使用 GeoJSON 与 PostGIS 一起工作,因此当您定义 Typeorm 模型时,您需要添加@types/geojson
,这将使您可以按照您的要求正确键入您的 Typeorm 列。
例如,您可以导入Geometry
类型定义并按如下方式键入您的列:
import { Geometry } from 'geojson';
...
@Column
location: Geometry
在您的情况下,您可能希望将您的latitude
和longitude
列组合成一个列location
——它可以使用该point()
函数将纬度和经度组合成一个Geometry
类型。
作为一个人为的示例,您可以执行以下操作:
UPDATE customers SET location = 'point(37.7, 122.4)' where id = 123;
这会将location
您customers
表上的列(作为示例)设置为geometry(point)
与旧金山的纬度/经度位置相对应的列类型。
如果您想将 lat/lon 的现有双精度列值(这是您应该自行存储 lat/lon 的方式)迁移到location
type 的单个列geometry(point)
,您可以使用ST_MakePoint
PostGIS 开箱即用的函数。
IE
-- Assuming you have a lat and lon columns on the `customers` table that you are migrating to the PostGIS geometry(point) type
UPDATE customers SET location = ST_MakePoint(lat, lon) where id = 123;
推荐阅读
- css - 如何将引导网站字体更改为 futura book?
- wordpress - Woocommerce 订单审核单个订单页面始终显示所有订单的 0% 增值税。为什么?
- django - 将模型条目显示为表格中的表单
- javascript - 与 ngOnInit() 和 ngAfterContentInit() 混淆
- javascript - Vue如何解决Uncaught SyntaxError: Function statements require a function name
- regex - 复杂匹配的正则表达式最小长度
- python - 如何删除唯一行并保留数据中的重复值
- bash - 在 shell 脚本中使用路径字符串时,它将被转换为包含子项的字符串
- c# - EF Core 2.2 AsNoTracking + Include 引发延迟加载错误。怎么修?
- postgresql - 等待服务 postgres 启动 dockerfile