javascript - 在定义 Sequelize 模型时运行行查询
问题描述
我已经定义了一个 Sequelize 模型,但我想要一个使用其他列查询结果的列。喜欢:
const test = sequelize.define('test', {
geom: {
type: DataTypes.GEOMETRY('POINT', 4326),
//value: sequelize.query(`SELECT ST_SetSRID(ST_MakePoint(${coordx}, ${coordy}),4326)`)
},
coordx: {
type: DataTypes.DECIMAL,
allowNull: false
},
coordy: {
type: DataTypes.DECIMAL,
allowNull: false
}
}, {
timestamps: false
})
如您所见,我想使用coordx和coordy并转换为 Geometry 并将其值添加到geom列
解决方案
Github 现在有一个未解决sequelize
的问题来支持. 但是,在问题底部提到的是mtkopone 发布的解决方法。根据他的建议,PostgreSQL 表可以有一个列定义为geom
as
create table if not exists test (
id bigserial not null,
geom geometry(point,4326) generated always as (ST_SetSRID(ST_MakePoint(coordx, coordy),4326)) stored,
coordx decimal not null,
coordy decimal not null,
constraint pk_testgeos primary key (id)
);
然后sequelize
模型可以定义为
let Test = sequelize.define('test', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
geom: {
type: 'geometry(point,4326) generated always as (ST_SetSRID(ST_MakePoint(coordx, coordy),4326)) stored',
set() {
throw new Error('geom is read-only')
}
},
coordx: {
type: DataTypes.DECIMAL,
allowNull: false
},
coordy: {
type: DataTypes.DECIMAL,
allowNull: false
}
}, {
timestamps: false,
tableName: 'test'
})
let test = await Test.create({
coordx: 3.14,
coordy: 3.14
}) // Some random place off the coast of Africa where hopefully they serve pie....
使用上述模式,对表的任何新插入或更新test
都将导致geom
列自动更新。请参阅PostgreSQL 的文档,其中讨论了生成的列。
geom
可以按如下方式访问属性的坐标(有关更多信息,请参阅sequelize 文档):
console.log(`Geometry type: ${test.geom.type}`)
console.log(`Geometry coordinates: ${test.geom.coordinates}`)