2011-08-30 175 views
0

在Grails中創建一個簡單的採購訂單應用程序,其中包含Category(例如:TV,Video ...),Brand和Item。品牌是相關的(hasMany)類別,例如索尼製造視頻和電視。如何將多個對象添加到Groovy中的對象屬性? ---在Bootstrap.groovy

裏面BootStrap.groovy中,我要做到以下幾點:

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) 

如何將品牌多個類別相關聯?注意我嘗試了很多不同的方法模板,但都沒有成功Brand類中的屬性是靜態的hasMany [categories:Category]。

回答

3

當你有static hasMany = [categories:Category]這增加了一個Set名爲categories到你的班級,並增加了一個動態的方法addToCategories這是做你想做的。它初始化集合,如果它爲空(對於新實例將是這種情況),然後將該實例添加到集合,並且如果它是雙向的,則設置反向引用。因此,那些最後三行應

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

這在user guide和每本書上Grails的描述,因爲它是映射集合的一個非常基本的功能。