標題重寫為:使用Sequelize統計關聯表的行數
P粉792026467
P粉792026467 2023-08-27 22:35:45
0
1
364
<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({ 其中: { 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({ 其中: { 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學習者快速成長!