Grails GORM域类关系的保存

时间:2018-06-07 03:01:36

标签: grails gorm

下面是域类结构

class User {
   String username
   String password
   String emailAddress
   static hasMany = [memberships: Membership]
}

class Membership {
   String name
   Integer memberPlanId
   static belongsTo = [user: User]
}

//MemberPlan data have 2 types of plan existed in DB
class MemberPlan {
   String type
   Float amount
}

我想要' memberPlanId'会员资格来自MemberPlan。我如何从那里设置,它应该属于belongsTo?以及如何保存查询此' memberPlanId'财产去了?

new User(username: 'input_username', password: 'input_password', emailAddress: 'input_emailAddress')
  .addToMemberShips(new Membership(name: 'input_name', memberPlanId: ?))
  .save()

1 个答案:

答案 0 :(得分:0)

您希望按如下方式编辑“成员资格”域

class Membership {
   String name
   MemberPLan memberPlan                 // this is basically a belongsTo relation
   static belongsTo = [user: User]
}

要保存新用户,您可以使用

new User(username: 'input_username', password: 'input_password', emailAddress: 'input_emailAddress')
  .addToMemberShips(new Membership(name: 'input_name', memberPlan: MemberPlan.get(1)))
  .save()

MemberPlan.get(1)将从id = 1

的数据库中获取记录

希望有所帮助