sequelize.js - Typescript sequelize 仅返回聚合函数,不返回任何其他字段
我有一个 Nest 项目,它连接到一个 Postgres 数据库。现在我有两张表,一张叫做“account”,另一张叫做“agent”。Account 与 Agent 之间有一对多的关系,如下所示。
@Table({
schema: "public",
name: {
singular: "accounts",
"plural": "accounts"
},
tableName: "accounts",
timestamps: false
})
export class Accounts extends Model<Accounts> {
@Column({field: "account_id", primaryKey: true})
accountId: number
@Column({field: "account_name"})
accountName: string
@Column({field: "created_at"})
createdAt: Date
@Column({field: "last_modify_date"})
lastModifyDate: Date
@Column
notes: string
@HasMany(() => Agent)
agents: Agent[]
}
@Table({schema: "public",
name: {
singular: "agent",
"plural": "agents"
},
tableName: "agents",
timestamps: false
})
export class Agent extends Model<Agent> {
@Column({field: "agent_id", primaryKey: true})
agentId: number
@Column({field: "last_update_time"})
lastUpdateTime: Date
@Column({field: "agent_name"})
agentName: string
@Column
timezone: string
@Column
language: string
@ForeignKey(() => Accounts)
@Column({field: "account_id"})
accountId: number
}
数据库是预定义的,所以我必须使用明确的字段名。
在 Nest 上运行时,我有一个“AccountService”,它旨在检索账户以及对我的数据进行一些聚合。例如,我希望能够通过账户 ID 获取一个账户,同时确定其任何代理最近的更改。因此,基本上,在 SQL 中,我希望将账户表与一个聚合连接起来:select max(last_update_time), account_id from agents group by account_id。
我在 Sequelize 中写了以下查询:
const retrievedAccount = await this.accountModel.findByPk(accountId, {
attributes: [
[fn('max', col('last_update_time')), 'latest_update_time'],
'Accounts.account_id',
'Accounts.account_name',
'Accounts.created_at',
'Accounts.last_modify_date',
'Accounts.notes'
],
include: [{
attributes: [],
model: Agent
}],
group: ['Accounts.account_id',
'Accounts.account_name',
'Accounts.created_at',
'Accounts.last_modify_date',
'Accounts.notes']
});
它确实有效,除了我的返回值,尽管我在属性中请求了 Accounts 表中的所有列,我在数据集中只得到“latest_update_time”:
这是生成的 retrievedAccount.toJSON():
{ "latest_update_time": "15:19:44.147562" }
我在这里做错了什么?
谢谢!