我当前的实体看起来像这样:
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Landmark extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
longitude: number
@Column()
latitude: number
}
但是我想知道是否有更好的方法可以通过typeorm使用特殊的postgres类型来做到这一点。
你将要研究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;