1

这是情况。我有一张表有多个多对多关系。

game (id, name, year_release ...)
game_price (game_id, price_id, amount)
price(id, label -- new game, used game)
category(id, name)
game_category(game_id, category_id)

现在我想选择一个包含 20 个游戏的列表,其中包含每个游戏的价格列表和类别列表。

在 SQL 中,我会做这样的事情

select game.id, game.name string_agg(price.label||':'game_price.amount), string_agg(category.name)
from game
left join game_price gp on (game.id = gp.game_id)
left join price on (price.id = price_id)
left join game_category gc on (game.id = gc.game_id)
left join category on (category.id = category_id)
group by game.id

我在这里有一个例子:http: //javalite.io/lazy_and_eager用于一对多,但没有用于多对多。

我是否必须先加载所有游戏价格,然后加载所有游戏类别,像这样?

List<GamesPrices> gamesPrices = GamesPrices.findAll(Game.class, Price.class)
List<GamesCategories> gamesCategories = GamesCategories.findAll(Game.class, Category.class)

但是,我怎样才能循环获取每个游戏的所有信息呢?

4

1 回答 1

1

有两种方法可以做到:

带型号:

List<Game> games = Game.where(criteria, param1, param2).include(Price.class, Category,class).limit(20);
for(Game g: games){
   List<Price> prices = g.getAll(Price.class);
   List<Category> categories = g.getAll(Category.class);
}

没有模型:

String sql = "select game.id, game.name string_agg(price.label||':'game_price.amount), string_agg(category.name)" + 
"from game" + 
"left join game_price gp on (game.id = gp.game_id)" + 
"left join price on (price.id = price_id)" + 
"left join game_category gc on (game.id = gc.game_id)" + 
"left join category on (category.id = category_id)" + 
"group by game.id";

List<Map> results = Base.findAll(sql);

我希望它有帮助!

于 2017-02-23T23:05:04.737 回答