search

Home  >  Q&A  >  body text

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>
P粉792026467P粉792026467474 days ago412

reply all(1)I'll reply

  • P粉193307465

    P粉1933074652023-08-28 11:56:53

    It only shows one because COUNT is an aggregate function that groups records for counting. So the only way to get both is to use a subquery, count the number of records in the join table, and get the records on the other side of the M:N relationship at the same time.

    const post = await Post.findOne({
      where: { id: postId },
      attributes: ["id", "title", "imageUrl", 
      // 你可能需要更正表和字段的名称
      [Sequelize.literal('(SELECT COUNT(*) FROM Likes where Likes.postId=Post.id)'), 'LikeCount']],
      include: [{
        model: User,
        as: "Likers",
        attributes: ["id"],
        through: { attributes: [] },
      }]
    })
    

    reply
    0
  • Cancelreply