Grails: Prevent cascading association between two domain classes with multiple relationships

前端 未结 3 590
攒了一身酷
攒了一身酷 2021-01-28 13:12

Consider two domain classes; Job and Quote.

A Job has many Quotes but a Job also has an accepted quote. The accepted quote is nullable and should only be set once a part

3条回答
  •  死守一世寂寞
    2021-01-28 13:50

    This may not be what you are looking for but I would actually model this a little differently - I would have an accepted flag in the Quote domain:

    class Job {
        String title
        static hasMany = [quotes: Quote]
    }
    
    class Quote {
        static belongsTo = [job: Job]
        BigDecimal quoteAmount
        Boolean accepted
    }
    

    Then your persistence could look like this:

    jobInstance.addToQuotes(new Quote(quoteAmount: 123.34, accepted: false)) //or true
    

    and no worries regarding your original problem.

    You could also add a transient and its getter to the Job class to get the accepted Quote

    class Job {
        String title
        static hasMany = [quotes: Quote]
    
        static transients = ['acceptedQuote']
    
        Quote getAcceptedQuote() {
            return Quote.findByJobAndAccepted(this, true)
        }
    
    }
    

提交回复
热议问题