Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Domain Class : hasOne, hasMany without belongsTo

I am new to Grails. Can I use "hasOne" or "hasMany" without using "belongsTo" to another domain-class?

Thanks in advance.

like image 394
Manazir Ahsan Avatar asked May 28 '14 07:05

Manazir Ahsan


1 Answers

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
}
like image 130
heikkim Avatar answered Sep 28 '22 04:09

heikkim