【问题标题】:ActiveJDBC select record from multiple tables with an aggregateActiveJDBC 从具有聚合的多个表中选择记录
【发布时间】:2017-07-14 14:10:19
【问题描述】:

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

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)

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

【问题讨论】:

    标签: postgresql activejdbc javalite


    【解决方案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);
    

    希望对你有帮助!

    【讨论】:

    • 我采用了第二种解决方案。第一个不起作用,因为模型游戏与模型价格没有关联。我收到此错误:java.lang.IllegalArgumentException:模型:com.myapp.models.Price 与:com.myapp.models.Game 无关。但是第二个解决方案是完美的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    相关资源
    最近更新 更多