Grails域类:hasOne,hasMany不属于 [英] Grails Domain Class : hasOne, hasMany without belongsTo
问题描述
我是Grails的新手。
我可以使用hasOne或hasMany而不使用belongsTo到另一个域的类吗?
预先感谢。
是的,你可以。请参阅Grails文档中的示例: http://grails.org/doc/2.3.8/guide/ GORM.html#manyToOneAndOneToOne
$ b 文档中的hasMany(without belongsTo)示例:
一个一对多关系是当一个类(示例Author)具有另一个类的许多
实例(例如Book)时。在Grails中,您可以使用hasMany设置定义
a关系:
static hasMany = [books:Book]
String name
}
class Book {
String title
}
在这种情况下,我们有一个单向的一对多。按照
的默认值,Grails会将这种关系映射到一个连接表。
hasOne(without belongsTo )示例:
示例C
class Face {
static hasOne = [nose:nose]
}
class鼻子{
脸孔
$ / code>
请注意,使用此属性会将外键与前面的例子相反的
表,所以在这种情况下,外键列
被存储在名为face_id的列内的鼻子表中。此外,
hasOne只适用于双向关系。
最后,在
的一边添加唯一约束是个好主意,一对一关系:
class Face {
static hasOne = [nose:鼻子]
静态约束= {
nose unique:true
}
}
class鼻子{
脸孔
}
I am new to Grails. Can I use "hasOne" or "hasMany" without using "belongsTo" to another domain-class?
Thanks in advance.
解决方案Yes, you can. See examples in Grails doc: http://grails.org/doc/2.3.8/guide/GORM.html#manyToOneAndOneToOne
hasMany (without belongsTo) example from the doc:
A one-to-many relationship is when one class, example Author, has many instances of another class, example Book. With Grails you define such a relationship with the hasMany setting:
class Author { static hasMany = [books: Book] String name } class Book { String title }
In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.
hasOne (without belongsTo) example from the doc:
Example C
class Face { static hasOne = [nose:Nose] } class Nose { Face face }
Note that using this property puts the foreign key on the inverse table to the previous example, so in this case the foreign key column is stored in the nose table inside a column called face_id. Also, hasOne only works with bidirectional relationships.
Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:
class Face { static hasOne = [nose:Nose] static constraints = { nose unique: true } } class Nose { Face face }
这篇关于Grails域类:hasOne,hasMany不属于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!