【问题标题】:sequelize - Specifying attributes for SELECT queries while using inner joinsequelize - 在使用内部联接时为 SELECT 查询指定属性
【发布时间】:2022-01-06 16:56:19
【问题描述】:

我想从主表中获取帐户并将其与帐户历史记录进行比较。 两个表之间存在 On To many 关系

SELECT account."userName", (account."postNumber" - accountHistory."postNumber") AS postNumber
    FROM public."Accounts" AS account  INNER JOIN public."AccountHistories" AS accountHistory
    ON account."userName" = accountHistory."userName" 
    WHERE accountHistory."scrappingDate" = '2022-01-08 23:59:39+01'
    ORDER BY postNumber DESC;

我的问题是如何使用 sequilize 进行查询? 我试过了,但我无法更改属性的名称并进行减法

await this.accountRepository.findAll({    
    where: {'$accountHistory.createdAt$' : '2022-01-08 23:59:39+01'},
    include: [{
      model: AccountHistory,
      required: false
    }],
    attributes: ['userName',['$accountHistory.postNumber $', 'postNumber '],postNumber ],
   order: [[$accountHistory.createdAt$', 'DESC']],
                    })

【问题讨论】:

    标签: javascript sql node.js sequelize.js nestjs


    【解决方案1】:

    您可能需要使用Sequelize.literal 作为别名属性执行计算,例如:

    const { literal } = require('sequelize')
    
    await this.accountRepository.findAll({    
        where: {'$accountHistory.createdAt$' : '2022-01-08 23:59:39+01'},
        include: [{
          model: AccountHistory,
          required: false
        }],
        attributes: [
          'userName',
          [
            literal('"account"."postNumber" - "accountHistory"."postNumber"'),
            'postNumber'
          ]
        ],
       order: [[$accountHistory.createdAt$', 'DESC']],
    })
    

    根据您的 SQL 方言,该确切语法可能不起作用 - 我不熟悉您使用的 $ 符号

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 2014-08-13
      • 2012-07-19
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      相关资源
      最近更新 更多