Access Relationship Table in Grails

☆樱花仙子☆ 提交于 2019-12-13 05:09:55

问题


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()
  {
      "${TypeName}"

  }
}

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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2477903/access-relationship-table-in-grails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!