Reputation: 1207
Having a tough time finding the answer to this in the Grails docs, the GIA book, or SO.
I'm grafting Grails onto a legacy database. I have two tables, and their relationship to each other is in an existing join table of foreign keys.
From what I've read, it seems that with the joinTable argument you can specify which field from the source table is used in the join table, but not the name of the foreign key column in the join table. One table in this database follows convention (the Video table has an id column and in the join table is called "video_id"; the other table does not (the PublisherCategory table has an id column, but is represented in the join table as "category_id."
When Grails starts up, it complains either about duplicate "id" fields, or, a non-existent field in the join table. (It's not clear to me from the docs whether the column argument in joinTable is the name of the column in that class that is used as a foreign key, or, if it's meant to be the name of the foreign key as it appears in the joinTable. Ive been working on the belief that it's the former. )
I also tried to create a domain class to represent join table itself, with hasMany relations for both source tables, but Grails didn't like that either. (It demands that one entity be the "owner", but setting either domain to owner didn't work.)
Any suggestions?
Upvotes: 1
Views: 1807
Reputation: 9895
The column argument in joinTable is not a foreign key, it's a value. For a many-to-many you need to set up the mapping from both directions. So with a schema like this:
VIDEO -|--------|< (video_id) THE_JOIN_TABLE (category_id) >|--------|- PUBLISHER_CATEGORY
can be modeled as Domain classes like this:
class PublisherCategory {
hasMany = [videos: Video]
static belongsTo = Video
static mapping = {
videos joinTable: [
name: 'the_join_table',
key: 'category_id'
]
}
}
class Video {
static hasMany = [categories: PublisherCategory]
static mapping = {
categories joinTable: [
name: 'the_join_table',
key: 'video_id'
]
}
}
Upvotes: 1