问题
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