cripox
cripox

Reputation: 542

Grails/GORM: What is the correct/best way to map these two domains?

I have a User domain class, and a List one.

Each list must have an author (a user) and each user must have a "primary list". Only some of the lists will have the "primaryList" statute.

So.. somthing like

 User:
    List primaryList

 List:
    User author

    static belongsTo = User

Of course this does not work as intended because the two relations are mistakenly taken as only one. I should also add a hasMany on the User and other belongsTo to the List..., but I don't want to complicate the example because I want to get the right answer from you.

Upvotes: 0

Views: 258

Answers (2)

Dana
Dana

Reputation: 676

You may need to use mappedBy to explain how the fields in User and List line up. Here are a couple domains that I wrote that allow a User to author many Lists but only set one to be "primary". There are a couple extra nullable constraints so you can use the scaffolded UI without getting into a chicken-and-egg scenario.

class User {
    String name
    FooList primaryList

    static hasMany = [authoredLists: FooList]

    static mappedBy = [primaryList: 'primaryOwner', authoredLists: 'author']

    static constraints = {
        primaryList nullable: true, unique: true
        authoredLists nullable: true
    }

    String toString() { name }
}

I named this class "FooList" just to avoid confusion with the standard List class:

class FooList {
    static belongsTo = [author: User, primaryOwner: User]

    static constraints = {
        primaryOwner nullable: true, display: false
    }
}

Upvotes: 3

Gregg
Gregg

Reputation: 35864

Try using the map belongsTo approach:

static belongsTo = [user:User]

That way Grails should see the 2 properties as separate.

Upvotes: 2

Related Questions