开发者

How do you add multiple Objects to an Object Attribute in Groovy? --- In Bootstrap.groovy

开发者 https://www.devze.com 2023-03-31 16:58 出处:网络
Making a simple purchase order application in Grails, wher开发者_如何学Pythone I have Category (eg: TV, Video...), Brand, and Item. A Brand is associated (hasMany) categories, for example Sony makes V

Making a simple purchase order application in Grails, wher开发者_如何学Pythone I have Category (eg: TV, Video...), Brand, and Item. A Brand is associated (hasMany) categories, for example Sony makes Video and TV's.

Inside Bootstrap.groovy, I want to do the following:

Brand jvc = new Brand(name:"JVC")
Brand sony = new Brand(name:"Sony")
Brand samsung = new Brand(name:"Samsung")

Category tv = new Category(name:"Television")
Category video = new Category(name:"Video")
Category laptop = new Category(name:"Laptop")

sony.categories.(tv)   ----> These methods are wrong
sony.addCategory(video) ----> These methods are wrong
sony.addCategory(laptop)

How do I associate the brand with multiple categories? Notice I tried many different method templates and neither worked. The attribute in the Brand class is static hasMany [categories:Category].


When you have static hasMany = [categories:Category] this adds a Set named categories to your class and adds a dynamic method addToCategories which does what you want. It initializes the set if it's null (will be the case for new instances), then adds the instance to the Set, and if it's bidirectional it sets the back-reference. So those last three lines should be

sony.addToCategories(tv)
sony.addToCategories(video)
sony.addToCategories(laptop)

This is described in the user guide and every book on Grails since it's a very fundamental feature of mapping collections.

0

精彩评论

暂无评论...
验证码 换一张
取 消