标题重写为:使用Sequelize统计关联表的行数
P粉792026467
P粉792026467 2023-08-27 22:35:45
0
1
366
<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粉792026467
P粉792026467

全部回复(1)
P粉193307465

它只显示一个,因为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: [] },
  }]
})
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!