[英]Many to Many association in Grails 4
我正在使用 Grails 4.0.1 開發一個新項目。 在這個項目中,我有兩個域類,第一個是Person
,第二個是Document
。 在這些類之間存在多對多關聯。 但是,我還需要在每個文檔中存儲每個人的順序(位置)。 有沒有辦法在 Grails 4 中模擬這種行為?
您必須將Document.persons
定義為List
:
class Document {
List<Person> persons
static hasMany = [ persons:Person ]
}
class Person {
static hasMany = [ documents:Document ]
}
有關更多信息,請參閱 參考文檔
幾個小時后,我得到了更適合我的用例的解決方案。 這是解決方案:
我們創建了兩個基類: Person
和Document
:
class Person { String name static hasMany = [documentPerson: DocumentPerson] static constraints = { name blank: false, nullable: false, maxSize: 255 documentPerson nullable: true } } class Document { String title static hasMany = [documentPerson: DocumentPerson] static mapping = { tablePerHierarchy false } static constraints = { title blank: false, maxSize: 255, nullable: true documentPerson nullable: true } }
接下來,我們定義類DocumentPerson
:
class DocumentPerson {
Integer position
Person person
Document document
static constraints = {
position nullable: false
document nullable: false
person nullable: false
}
}
此時,我們按照預期在數據庫中有三個表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.