简体   繁体   English

用于保存的Grails GORM域类关系

[英]Grails GORM domain class relation for saving

below is the domain class structured 下面是结构化的领域类

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
}

I want the 'memberPlanId' of Membership to reference from MemberPlan. 我希望会员资格的“ memberPlanId”从MemberPlan引用。 How do I set from there, it should be under belongsTo? 我如何从那里设置,它应该在belongsTo下? And how does the saving query for this 'memberPlanId' property goes? 这个“ memberPlanId”属性的保存查询如何进行?

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

You would want to edit the Membership domain as follows 您可能要按以下方式编辑成员资格域

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

To save a new user you can use 要保存新用户,您可以使用

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) will fetch the record from the database with id = 1 MemberPlan.get(1)将从数据库中获取ID = 1的记录

Hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM