开发者

Access Relationship Table in Grails

I have the following domains classes:

class Posts{
      String Name
      String Country
      static hasMany = [tags:Tags]

        static constraints = {
        }
    }


class Tags{

    String Name
    static belongsTo = Posts
    static hasMany = [posts:Posts]
    static constraints = {
    }
  String toString()
  {
      "${T开发者_运维百科ypeName}"

  }
}

Grails creates an another table in the database i.e. Posts_Tags.

My requirement is:

E.g. 1 post has 3 tags. So, in the Posts_Tags table there are 3 rows.

How can I access the table Posts_Tags directly in my code so that I can manipulate the data or add some more fields to it.


If you want to access the join table (Posts_Tags) directly, or add properties to it, then you must define it as a separate PostTag domain class. You then split your many-many relationship between Post and Tag into 2 one-to-many relationships (one from Post to PostTag and one from Tag to PostTag).

Here's a comprehensive example of how to perform the mapping and add properties to the join table - in this example Membership is the join table.


Use the normal groovy sql API. For an example of how to get a groovy SQL object and execute sql queries see this

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜