我正试图在Grails 3.3.8中将具有关系的域呈现为JSON。
我已经渲染了一个名为Round
的域,其中包含许多RoundItem
,然后我添加了另一个名为AnswerOptions
的域,该域属于RoundItem
。如何从控制器获取该域属性以将其全部呈现为JSON?
代码如下:
圆形:
class Round {
String name
String comments
Date date
Boolean enable
static hasMany = [items: RoundItem, answers: RoundAnswer]
}
RoundItem:
class RoundItem {
String name
String comments
String image
String type
static belongsTo = [round: Round]
static hasMany = [items: RoundItem, answers: RoundAnswerItem, options: AnswerOption]
}
AnswerOption:
class AnswerOption {
String option
String type
static belongsTo = [item: RoundItem]
}
呈现域的控制器方法:
@Transactional
def round(){
Round round = Round.get(params.id)
RoundItem roundItem = RoundItem.get(params.id)
if(!checkEnableToRound(round)){
render status: METHOD_NOT_ALLOWED, text: '{"message":"Ya han tomado la prueba"}'
return
}
def items = []
round.items.each{
def item = [
id: it.id,
name: it.name,
comments: it.comments,
image: it.image,
answer: ''
]
items.push(item)
}
Student student = springSecurityService.currentUser.student
RoundAnswer answer = RoundAnswer.findByRoundAndGroup(round,student.group)
if(!answer){
answer = new RoundAnswer(
round: round,
group: student.group,
userCreated: student.id,
userUpdated: student.id
)
answer.save(failOnError:true, flush:true)
}
def data = [
id: round.id,
name: round.name,
comments: round.comments,
items: items,
start: answer.dateCreated,
limit: checkLimit(answer.dateCreated)
]
render data as JSON
}