RyanLynch
RyanLynch

Reputation: 3007

Add dateCreated field to join table in Grails

I have a M:M relationship between User and Badge which creates a join table called "user_badges". This table has the fields: user_id and badge_id. Is there a way to get the standard date_created fields on this table?

class Badge {

static belongsTo = User
static hasMany = [users: User]
}

class User {
 static hasMany = [badges: Badge]
}

Upvotes: 4

Views: 1229

Answers (3)

Ajay Gopal Shrestha
Ajay Gopal Shrestha

Reputation: 199

I am doing same kind of research. May be this is a better way.Please comment below if I am wrong.

class Badge {    
  /* Declare Variables */
  static belongsTo = [BadgeOwner]
}

class User {
  /* Declare Variables */
  static belongsTo = [BadgeOwner]
}

class BadgeOwner {
  User user
  Badge badge
  Date dateCreated 
  Date lastUpdated
}

Upvotes: 0

Dónal
Dónal

Reputation: 187529

Basically, you need to change the mapping so that the M:M relationship is expressed as two 1:M relationships. Here's an example where the joining class is BadgeOwner (so by default the generated join table will be named badge_owner)

class Badge {    
  static hasMany = [owners: BadgeOwner]
}

class User {
  static hasMany = [owners: BadgeOwner]
}

class BadgeOwner {
  static belongsTo = [user: User, badge: Badge]
  Date dateCreated 
  Date lastUpdated
}

Upvotes: 6

jpkroehling
jpkroehling

Reputation: 14061

If it has additional properties, it's not a join table. It's a separate entity. So, map it accordingly :-)

Upvotes: 4

Related Questions