The title is rewritten as: Use Sequelize to count the number of rows in related tables
<p>Using sequelize and mySQL, I have two tables: <code>User</code> and <code>Post</code>. </p>
<p>The relationship between the two tables is <code>M:N</code></p>
<pre class="brush:php;toolbar:false;">db.User.belongsToMany(db.Post, { through: "Likes", as: "Liked" });
db.Post.belongsToMany(db.User, { through: "Likes", as: "Likers" });</pre>
<p>What I want is to get all the liker ids and the number of likers of the post. </p>
<p>I know you can get <code>all likers</code> like this. </p>
<pre class="brush:php;toolbar:false;">const post = await Post.findOne({
where: { id: postId },
attributes: ["id", "title", "imageUrl"],
include: [{
model: User,
as: "Likers",
attributes: ["id"],
through: { attributes: [] },
}]
})
// result
{
"id": 36,
"title": "test",
"imageUrl": "하늘이_1644886996449.jpg",
"Likers": [
{
"id": 13
},
{
"id": 16
}
]
}</pre>
<p>Also, I also know that I can get the <code>number of likes</code> this way. </p>
<pre class="brush:php;toolbar:false;">const post = await Post.findOne({
where: { id: postId },
attributes: ["id", "title", "imageUrl"],
include: [{
model: User,
as: "Likers",
attributes: [[sequelize.fn("COUNT", "id"), "likersCount"]],
}]
})
// result
{
"id": 36,
"title": "test",
"imageUrl": "하늘이_1644886996449.jpg",
"Likers": [
{
"likersCount": 2
}
]
}</pre>
<p>However, I don't know how to get both of them at the same time.
Check the results when I use them both. </p>
<pre class="brush:php;toolbar:false;">{
model: User,
as: "Likers",
attributes: ["id", [sequelize.fn("COUNT", "id"), "likersCount"]],
through: { attributes: [] },
}
// result
"Likers": [
{
"id": 13,
"likersCount": 2
}
]</pre>
<p>It only shows one liker (id: 13)
It should show another liker (id: 16). </p>
<p>What is the problem? </p>