Grails / GORM: Creating a One-to-One Relationship

I am developing a system in which posts / discussions between users can be updated to become tickets. In one specific place, I am trying to create a one-to-one relationship, but I am facing certain problems. The following is a concise version of the objects in focus.

Rules:

  • The message may become a Ticket if required. (Not necessary)
  • The ticket must have a message. (Required)

Post.groovy

class Post { String title String description String postedBy Ticket ticket static hasMany = [comments: Comment] static constraints = { title(blank:false) description(blank:false) postedBy(blank:false) ticket (nullable:true,unique:true) } } 

Ticket.groovy

 class Ticket { String title String description String postedBy Post post static hasMany = [responses: Response] static constraints = { title(blank:false) description(blank:false) postedBy(blank:false) post (nullable:false,unique:true) } } 

It works to some extent. I can:

  • Create a message that leaves the ticket attribute null If and when the message is updated to become a ticket
  • I can explicitly set the Mail Ticket attribute to indicate the parent ticket.

However, this mapping is not performed at the domain level. It leaves room for a situation where Ticket1 points to Post1, but Post1 points to Ticket2.

I tried using static hasOne = [post: Post] in the Ticket class, but later found out that it specifies the presence of static belongsTo = [ticket: Ticket] in the Post class, and this becomes 1-to-1 binding, which is not what I'm looking for.

Is there a way to achieve this 1-to-1 optional mapping in this scenario? Any pointers would be most helpful.

+6
source share
1 answer

You might consider creating a custom validator like

 class Post { // Other fields Ticket ticket static constraints = { // Other constraints ticket (nullable:true,unique:true, validator: { val, obj -> if(val) { return val.post == obj } }) } } 

Did this solve your problem?

+3
source

Source: https://habr.com/ru/post/898814/


All Articles