gpt4 book ai didi

javascript - Sequelize 不能包含 count 属性

转载 作者:行者123 更新时间:2023-11-28 03:14:21 28 4
gpt4 key购买 nike

伙计们。我有以下问题。我有两个实体,其中一个事件可以有许多参与者,如下所示:

class Event {
name: string;
participants: Participant[];
}

class Participant {
eventId: string;
event: Event;
fullName: string;
}

我想创建一个查询,它将统计我的参与者数量。所以我创建了一个像这样的查询:

await Event.findAll({
attributes: [
"Event.id",
"participants.id",
[Sequelize.fn("COUNT", Sequelize.col("participants.id")), "participantCount"],
],
include: [
{
model: Participant,
as: "participants",
required: false,
attributes: ["id"],
},
],
raw: true,
group: ["Event.id", "participants.id"],
});

但是问题是执行过程中出现错误,如下:

"message": "attr[0].indexOf is not a function",
"stack": "TypeError: attr[0].indexOf is not a function\n at attributes.map.attr

我的sequelize版本是4.41.1。你有遇到这样的错误吗?如果是的话,我将非常感谢您的帮助。

最佳答案

由于您只需要计数,因此可以使用两种方法 - Sequelize QueryRaw Query

序列化查询

    Event.findAll({
attributes: [
"id",
[Sequelize.literal('SELECT COUNT(*) FROM participants P WHERE
P.eventId=events.id'), "participantCount"]
]
});

原始查询

    Db.sequelize.query(`
SELECT E.id,
(SELECT COUNT(*) FROM participants P WHERE P.eventId=E.id) as participantCount
FROM events E
`, {
type: Sequelize.QueryTypes.SELECT,
});

** 这里的 Db 是 Sequelize 连接。

关于javascript - Sequelize 不能包含 count 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59769798/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com