简体   繁体   English

为grails中的相同域类创建一对多和多对多

[英]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. 这篇文章看起来与我的问题类似,但我没有得到,请帮助。

First, order is a reserved word in SQL. 首先, order是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. 由于GORM默认情况下会创建一个与您的类同名的表,因此您需要重命名您的类或提供在映射到SQL表时使用的其他名称。

For example: 例如:

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

Another problem is that Order contains two associations to User . 另一个问题是Order包含两个与User关联。 You need to tell GORM which one of these that is the bi-directional association from User to Order . 您需要告诉GORM这些中的哪一个是从UserOrder的双向关联。 That can be achieved using mappedBy , like this: 这可以使用mappedBy实现,如下所示:

class User {
    String userName

    static hasMany = [orders: Order]
    static mappedBy = [orders: 'owner']

}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM