簡體   English   中英

在 Objection.js 中按急切結果計數排序記錄並實現分頁?

[英]Order records by eager results count and implement pagination based on that in Objection.js?

我有這些表:

  1. Users
  2. Skills
  3. Has_skills (user_id, skill_id)

我將一系列技能 ID 傳遞給 function,它應該獲取至少具有其中一項技能的用戶。 查詢在某種程度上應該是有效的,因此它獲取多個用戶(限制、范圍或換句話說分頁功能),但不執行從 ID 為 0 的用戶開始然后向上的范圍,而是從用戶開始的范圍最匹配的技能最少。

那么查詢如何按匹配技能的數量從最匹配技能到最少對記錄進行排序,以便我可以根據這些結果添加分頁? 我想我應該另外調整 has_skills 上的 modifyEager 並計算它,然后實現分頁范圍,但我不完全確定如何做到這一點。 所以最終,這就是我需要添加的內容:

  1. 查詢應首先按匹配技能的數量對記錄進行排序/排序
  2. 上述條件應受用戶數量或范圍的限制,以實現分頁目的和更好的性能

這是我的 function:

async function getUsersWithPassedSkillIds({ skillIds }) {
    const users = await User.query()
        .select('users.id', 'users.name')
        .joinEager('has_skills')
        .modifyEager('has_skills', builder => builder.select('id', 'name'))
        .whereIn('has_skills.id', skillIds)

    return users
}

Objection.js 的作者幫助我完成了這項工作!

 // Fetch the users who have at least one matching skill const hasSkillsSubquery = User.relatedQuery("skills").whereIn( "has_skills.skill_id", skillIds ); const users = await User.query().select("users.id", "users.name") // Use.eager instead of.joinEager as pagination doesn't work with it due to joins. .eager("skills") // Optional: Populating the matched skills.modifyEager("skills", builder => builder.select("skills.id", "skills.name").whereIn("skills.id", skillIds) ) // Only taking into account users who have at least 1 matched skill.whereExists(hasSkillsSubquery.clone()) // Sorting users by matched skills.orderByRaw("(?) DESC", hasSkillsSubquery.clone().count()) // This would return the user with the most matched skills. // If you want to fetch 10 users ordered by number of matching skills: .range(0, 9).range(0, 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM