【问题标题】:Running a row query while defining Sequelize model在定义 Sequelize 模型时运行行查询
【发布时间】:2021-09-02 00:33:28
【问题描述】:

我已经定义了一个 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
})

如您所见,我想使用 coordxcoordy 并转换为 Geometry 并将其值添加到 geom

【问题讨论】:

  • geom列是否存在于数据库中,还是续集virtual column?如果有可能只有一个 PostgreSQL generated column 然后将其映射到 sequelize 中的 DataTypes.GEOMETRY 属性,那么除非 coordx 或 coordy 在数据库中发生更改,否则您不必重新计算它,对吧?
  • 假设该列在 DB 中,但没有任何价值。在每一行中,它从 coordx 和 coordy 计算中获取其值。
  • 我做了更多的挖掘工作,看起来可能有更好的方法来代替虚拟列的续集。我试图在下面的答案中解释。希望这会有所帮助!

标签: javascript node.js sequelize.js


【解决方案1】:

Github 现在有一个open issue 来支持sequelize 中的只读列。但是,在问题底部提到的是workaround posted by mtkopone。根据他的建议,PostgreSQL 表可以有一个geom 的列定义为

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's documentation 他们谈论生成的列。

geom 属性的坐标可按如下方式访问(请参阅sequelize docs 了解更多信息):

console.log(`Geometry type: ${test.geom.type}`)
console.log(`Geometry coordinates: ${test.geom.coordinates}`)

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 2022-01-26
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多