[英]Many to Many relationship in grails
我正在grails / Gorm中嘗試多對多關系示例。 下面是到目前為止我嘗試過的代碼。當我嘗試分析不同的情況時,我想知道Gorm休眠如何處理它。
class Author {
static hasMany = [books:Book]
String name
}
class Book {
static belongsTo = Author
static hasMany = [authors:Author]
String title
}
And in my controller i defined this way in order to add Authors and books.
def a=new A(name:"ABC")
def b=new B(title:"Code1")
a.addToB(b)
def a=new A(name:"ABC")
def b=new B(title:"Code2")
a.addToB(b) //It works.
In the databaselevel it creates
Table Author Table Author-Book Table Book
id name id id id Book
1 ABC 1 1 1 Code1
2 ABC 2 2 2 Code2
But what i want is the below format:
Table Author Table Author-Book Table Book
id name id id id Book
1 ABC 1 1 1 Code1
1 2 2 Code2
將作者姓名設置為唯一時,如何實現?
您的域設置很好。 您將顯式創建兩個作者(具有相同的姓名)。 我將您的代碼更改為
def a=new A(name:"ABC")
def b=new B(title:"Code1")
a.addToB(b)
def a= A.findOrSaveByName("ABC") // this will attempt to query the db first and only create new record it already doesn't exist
def b=new B(title:"Code2")
a.addToB(b) //It works.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.