gpt4 book ai didi

grails - 迭代时访问Grails中的另一个数据库表

转载 作者:行者123 更新时间:2023-12-02 14:30:30 25 4
gpt4 key购买 nike

我有这些模特

游戏规则

class Game {
String gameTitle
static hasMany = [screenshot: Screenshots list:GameList]
}

GameList.groovy
class GameList {
static belongsTo = [game : Game , category : GameCategory]
static constraints = {
}
}

GameCategory.groovy
class GameCategory {
String categoryName
String icon
String toString(){
"${categoryName}"
}
static hasMany = [ list:GameList]
static constraints = {
}
}

在我的 Controller 中
GameController.groovy
def listGame(){
def category = GameCategory.list()
def currentCategory = params.categoryName
def myCategory=GameCategory.findByCategoryName(currentCategory)
def game = GameList.findAllByCategory(myCategory).collect{it.game}
[currentCategory:currentCategory, category:category, game:game]
}

在我看来,我迭代了所有游戏以显示特定类别中的每个游戏。
另外,我想显示每个游戏的所有类别。如何在每次迭代中访问每个游戏的类别?

最佳答案

对于您的域模型,您无法从Game实例访问游戏类别,因为无法导航从GameGameCategory的关联。保持相同的域模型,这是一个技巧:

def listGame(){
def category = GameCategory.list()
def currentCategory = params.categoryName
def myCategory=GameCategory.findByCategoryName(currentCategory)
def game = GameList.findAllByCategory(myCategory).collect{it.game}
def gameCategories = GameList.withCriteria {
inList 'game', game

projections {
property 'game'
property 'category'
}
}.groupBy { it[0] }
.collectEntries { game, record -> [(game): record*.getAt(1)] }

[currentCategory:currentCategory, category:category, game:game, gameCategories: gameCategories]
}

宽松地说, gameCategoriesMap<Game, List<GameCategory>>,其中包含 GameCategory变量中每个 Game的所有 game。您可以将其传递到 View ,并使用它来查找 GameCategoryGame: def categories = gameCategories[gameInstance]
但是,您可以使用不同的域模型来简单地完成所有这些操作,如下所示:

替代领域模型(Domain Model)
class Game {
String gameTitle
static hasMany = [screenshot: Screenshots, categories: GameCategory]
}

class GameCategory {
String categoryName
String icon
String toString(){
"${categoryName}"
}
static hasMany = [games: Game]
static constraints = {
}
}

现在, Game具有许多 GameCategory,而 GameCategory具有许多 Game。使用这种模型,可以简化 listGame():
def listGame(){
def currentCategory = params.categoryName
def myCategory=GameCategory.findByCategoryName(currentCategory)
def games = myCategory.games

[currentCategory:currentCategory, games: games]
}

然后,您可以在 View 中呈现如下游戏和类别:
<g:each var="game" in="${games}">
<!-- Render game -->
<g:each var="category" in="${game.categories}">
<!-- Render the game's category -->
</g:each>
</g:each>

关于grails - 迭代时访问Grails中的另一个数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33633081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com