在Grails中访问关系表 [英] Access Relationship Table in Grails

查看:135
本文介绍了在Grails中访问关系表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class文章{
字符串名称
字符串国家
static hasMany = [标签:标签]

静态约束= {
}
}


类标签{

字符串名称
static belongsTo =帖子
static hasMany = [帖子:帖子]
static constraints = {
}
String toString()
{
$ {TypeName}

}
}

Grails在数据库中创建另一个表,即Posts_Tags。

我的要求是:

例如1发布有3个标签。
因此,在Posts_Tags表中有3行。



如何直接在我的代码中访问表Posts_Tags,以便我可以操作数据或添加如果你想访问连接表( Posts_Tags ), c $ c>),或者向它添加属性,那么你必须将它定义为一个单独的 PostTag 域类。然后,将 Post Tag 之间的多关系拆分为2个一对多关系(一个来自发布邮政标签和一个从标签 PostTag )。



这是综合示例,介绍如何执行映射并向连接表添加属性 - 在本例中 Membership 是连接表。


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.

解决方案

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.

这篇关于在Grails中访问关系表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆