Bernhard
Bernhard

Reputation: 444

grails gorm - not usual one-to-many association - bug found?

first of all: i am not a beginner in grails. I used a one-to-many association many times. Maybe the problem is happening because it's not a usual use.

The code:

class Filter {

      static hasMany = [normal:Result, longerDates:Result, locationReduce1:Result, locationReduce2:Result]
}

class Result {

    int score

    static belongsTo = [user:User, filter:Filter]

    static constraints = {
        user(nullable:false, blank:false)
        score(nullable:false)
}

as you can see. i am using the Class "result" 4-times as a one to many association to the same class "filter"

grails creates the table "result" with a foreign key "filter_id" to reference to the associated filter. But no difference is made if its the "normal"/ "longerDates" .... association. As a result when i query

def results = filter.normal

or

def results =filter.longerDates

i get the same results. although i saved the results right

filter.addToNormal(new Result(..))

and

filter.addToLongerDates(new Result(..))

the next thing i tried was deleting the belongs_to association from the result to the filter. Although i wanted to implicitly delete all results of a filter when the filter is deleted...

the result was a "result" table as i wanted it. 4 attributes called "normal" "longer_dates", "location_Reduce_1" and "location_Reduce_2". when i saved a "normal" result the attribute in the table contained the filter id to which the result belongs. the other attributes (like longerDates" had the null value). so far so good. the strange thing that i was only able to save ONE result per filter although i had a has_many attribute in the "filter" class

has anybody any idea what i am doing wrong?

Upvotes: 0

Views: 285

Answers (1)

yogiebiz
yogiebiz

Reputation: 386

I think you should use the mappedBy property in Filter class

class Filter {

    static hasMany = [normal:Result, longerDates:Result, locationReduce1:Result, locationReduce2:Result]
    static mappedyBy = [normal: "normalFilter", longerDates: "longerDatesFilter", locationReduce1: "locationReduce1Filter", locationReduce2: "locationReduce2Filter"]
}

class Result {
    static belongsTo = [normalFilter: Filter, longerDatesFilter: Filter, locationReduce1: Filter, locationReduce2Filter: Filter]
}

The reference is here

Upvotes: 3

Related Questions