Search code examples
grailsgroovygrails-2.0groovy-console

Creating one-to-many & many-to-many for same domain class in grails


I want to create a domain class as like , One user can post many orders [Bidirectional] and one order can be liked by many users [unidirectional].

I have written a domain class as shown below ,

Class User {

  String userName;

  List orders 

  static hasMany = [Order]
}

Class Order {

    String orderId

    String orderName

       //Indicates this order belongs to only one user
    static belongsTo =[owner : User ]  // Bidirectional

    //Indicates order can be liked by many users
    static hasMany = [likedUser : User]   //Unidirectional
 } 

But I am getting am error saying invalid schema . Any body please help...

This post looks similar to my question but I am not getting , Please help.


Solution

  • First, order is a reserved word in SQL. Since GORM by default creates a table with the same name as your class, you'll need to either rename your class or provide a different name to use when mapping to SQL tables.

    For example:

    class Order {
        static mapping = {
            table 'user_order'
        }
        // ...
    }
    

    Another problem is that Order contains two associations to User. You need to tell GORM which one of these that is the bi-directional association from User to Order. That can be achieved using mappedBy, like this:

    class User {
        String userName
    
        static hasMany = [orders: Order]
        static mappedBy = [orders: 'owner']
    
    }
    

    Hope this helps.