首页  >  问答  >  正文

标题重写为:使用Sequelize统计关联表的行数

<p>使用sequelize和mySQL,我有两个表:<code>User</code>和<code>Post</code>。</p> <p>两个表之间的关系是<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>我想要的是获取帖子的所有点赞者id和点赞者数量。</p> <p>我知道可以这样获取<code>所有点赞者</code>。</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: [] }, }] }) // 结果 { "id": 36, "title": "test", "imageUrl": "하늘이_1644886996449.jpg", "Likers": [ { "id": 13 }, { "id": 16 } ] }</pre> <p>而且,我也知道可以这样获取<code>点赞者数量</code>。</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"]], }] }) // 结果 { "id": 36, "title": "test", "imageUrl": "하늘이_1644886996449.jpg", "Likers": [ { "likersCount": 2 } ] }</pre> <p>但是,我不知道如何同时获取它们两个。 当我同时使用它们时,检查结果。</p> <pre class="brush:php;toolbar:false;">{ model: User, as: "Likers", attributes: ["id", [sequelize.fn("COUNT", "id"), "likersCount"]], through: { attributes: [] }, } // 结果 "Likers": [ { "id": 13, "likersCount": 2 } ]</pre> <p>它只显示了一个点赞者(id: 13) 它应该显示另一个点赞者(id: 16)。</p> <p>问题是什么?</p>
P粉792026467P粉792026467419 天前375

全部回复(1)我来回复

  • P粉193307465

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

    它只显示一个,因为COUNT是一个聚合函数,它将记录分组以进行计数。所以要同时获取两者的唯一方法是使用子查询,在连接表中计算记录的数量,同时获取M:N关系的另一端的记录。

    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: [] },
      }]
    })
    

    回复
    0
  • 取消回复