簡體   English   中英

比較Grails中的域對象之間的關聯

[英]Compare associations between domain objects in Grails

我不確定是否要采用最佳方法,但是我將盡力解釋我要做什么。

我有以下領域課程

類User {static hasMany = [目標:目標]}

因此,每個用戶都有一個目標對象列表。 我希望能夠獲得一個User實例,並在其目標列表中返回5個用戶(具有該實例)的匹配Goal對象數量最多。

有人可以請我解釋一下我該怎么做嗎?

實現此目的的最簡單,最有效的方法是使用普通SQL。 假設您有這些表

users      [id]
goals      [id, description]
user_goals [user_id, goal_id]

您可以使用以下查詢執行所需的操作:

set @userId=123;
select user_id, count(*) as matched from user_goals
where user_id!=@userId
  and goal_id in (select ug.goal_id from user_goals ug where ug.user_id=@userId)
group by user_id order by matched desc limit 5;

這將獲取一個用戶ID,並返回具有匹配目標的其他用戶的列表,並按匹配次數排序。 將其包裝在GoalService ,您就完成了!

class GoalService {
  def findUsersWithSimilarGoals(user) {
    // ...
  }
}

也可以使用條件或HQL來執行此操作,但是使用此類查詢通常更容易使用SQL。

如果您正在尋找簡單的匹配項,那么最簡單的方法可能是對每個目標進行一次findAll,然后計算每個其他用戶出現在結果中的結果數:

Map user2Count = [:]
for (goal in myUser.goals){
    for (u in User.findAllByGoal(goal)){
         def count = user2Count.containsKey(u) ? user2Count.get(u) : 0
         count++
         user2Count.put(u, count)
    }
}
// get the top 5 users
def topUsers = user2Count.entrySet().sort({ it.value }).reverse()[0..5]

根據您的需要,這可能太慢,但是很簡單。 如果許多用戶共享相同的目標,則可以緩存findAllByGoal的結果。

暫無
暫無

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

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