2017-02-14 53 views
1

額外的字段我有3個表:多到許多activejdbc

person (person_id, person_name), 
game (game_id, game_name) 

和連接表

play(person_id, game_id, score). 

隨着ActiveJdbc我用many2many註釋並能正常工作以獲取所有遊戲1人

List<Game> games = person.get(Game.class, "person_id = ?", personId); 

我的問題是如何獲得值「分數」? 我試過game.getScore(),但它顯然沒有工作

編輯: 我想從1人的完整遊戲列表。下面是結果我想

game1 | 21 
game2 | 33 
game3 | 44 

在SQL中應該是這樣的:

select game.name, play.score 
from game join play on (game.game_id = play.game_id) 
join person on (game.person_id = person.person_id) 
where person_id = 1; 

回答

1

有可能是這樣做的不止一種方法,但這裏是一個方式。您可以將多對多關係視爲兩個一對多關係,其中,Play是Person和Game兩者的孩子。然後你從不同的角度來處理:

List<Play> plays = Play.where("person_id = ?", 1).include(Person.class, Game.class); 

使用include()你也優化和運行更少的查詢:http://javalite.io/lazy_and_eager

根據您的查詢條件,你可能只有一個打法:

Game game = plays.get(0).parent(Game.class); 
Person = plays.get(0).parent(Person.class); 

如果當然,你能夠得到你的分數:

int score = plays.get(0).getScore(); 

希望它能幫助!

+0

好的,感謝編輯我的文章。爲了你的回答,我真的不明白。我想要的是顯示1個給定人的戲劇列表+得分。我編輯了我的帖子。但是從你的答案來看,我必須從「遊戲」中獲得分數,但在我的模型中(「遊戲」),我沒有「getScore」方法,這導致我得到:在com類型上找不到「財產」分數.myapp.models.Game。當我在jsp頁面 – Rony

+0

中使用它時,我的代碼中有一個拼寫錯誤,只是修復了。由於您在Play上獲得分數,因此您可以從該對象中獲取分數。 – ipolevoy

+0

啊好的!得到它了!現在的作品,我用包括像你說的:)謝謝很多! – Rony