[英]Sequelize cannot include with count attribute
guys.伙计们。 I have the following problem.
我有以下问题。 I've got two entities, where one event can have many participants like the following:
我有两个实体,其中一个事件可以有许多参与者,如下所示:
class Event {
name: string;
participants: Participant[];
}
class Participant {
eventId: string;
event: Event;
fullName: string;
}
I would like to create a query, which will count for me numbers of participants.我想创建一个查询,这将计算我的参与者数量。 So I created a query like this:
所以我创建了一个这样的查询:
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"],
});
But the problem is with an error during exacution as follow:但问题是在执行过程中出现错误如下:
"message": "attr[0].indexOf is not a function",
"stack": "TypeError: attr[0].indexOf is not a function\n at attributes.map.attr
My version of sequelize is 4.41.1.我的续集版本是 4.41.1。 Have you got this kind of error?
你有过这种错误吗? If yes, I will be very grateful for the help.
如果是,我将非常感谢您的帮助。
Since you only need the count you can use two methods - Sequelize Query or Raw Query由于您只需要计数,您可以使用两种方法 - Sequelize Query或Raw Query
Sequelize Query序列化查询
Event.findAll({
attributes: [
"id",
[Sequelize.literal('SELECT COUNT(*) FROM participants P WHERE
P.eventId=events.id'), "participantCount"]
]
});
Raw Query原始查询
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 here is the sequelize connection. ** 这里的 Db 是续集连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.