【问题标题】:How do I convert SQL query to sequelize?如何将 SQL 查询转换为 sequelize?
【发布时间】:2020-03-22 14:30:20
【问题描述】:

我有这个 sql 块 - 我正在使用 postgres DB。 如何将此查询转换为 sequelize ORM 格式?谢谢

select 
    to_char (created_at,'Mon') as month,
    extract (year from created_at) as year,
    id_product as product ,
    sum (sales) as sales
from 
    toiletries
group by 
    1, 2, 3

【问题讨论】:

  • 我想你不能使用续集模型来做到这一点。只能通过原始 SQL 查询。

标签: sql node.js orm sequelize.js


【解决方案1】:

你可以通过使用 sequelize.literals() 来达到这个目的

const Toiletries = sequelize.define('toiletries', {
    id_product: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    productName: {
        type: Sequelize.TEXT,
    }
    sales: {
     type: Sequelize.INTEGER,
    }
}, {
    freezeTableName: true,
    tableName: 'toiletries'
});
Toiletries.findAll({
  group: ['id_product', 'createdAt'],
  attributes: [
    ['id_product', 'product'],
    [sequelize.literal('extract(YEAR FROM "createdAt")'), 'year'],
    [sequelize.literal('sum (sales)'), 'sum']
  ]
}).then((inn) => {
  console.log(JSON.stringify(inn))
});

您需要对“to_char”列进行一些挖掘。如果您提供表结构,我们也可以提取它。

【讨论】:

  • 感谢您的回答,我会尝试执行您发布的查询并让您知道结果
猜你喜欢
  • 2022-11-21
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2020-07-19
  • 2021-10-11
  • 2017-10-29
相关资源
最近更新 更多