WaZ
WaZ

Reputation: 1757

Grails - Self-referencing relationships

When I write the following class, I get the following compilation error:

could not resolve property

How can I achive the following:

class Employee{
  String Name
  String Email
  Employee Manager
  static hasMany = [desginations:Designation]    

  static constraints = {
  Name(unique:true)
  Email(unique:true)
  }

Thanks, Much appreciated.

Upvotes: 1

Views: 2795

Answers (1)

ataylor
ataylor

Reputation: 66109

GORM can be picky about following its naming convention. In particular, field names should be camelCase, starting with a lower case letter.

With the following definition:

class Employee {
    String name
    String email
    Employee manager

    static constraints = {
        name(unique:true)
        email(unique:true)
        manager(nullable:true)
    }
}

I can create an employee with a manager like so:

manager = new Employee(name: 'manager', email: '[email protected]')
manager.save()
employee = new Employee(name: 'employee', email: '[email protected]')
employee.manager = manager
employee.save()

Edit: As fabien7474 noted, the important part is the manager(nullable:true) constraint. This allows employee records to be saved without assigning a manager. In the above example, the employee named manager is employee's manager, but manager itself doesn't have a manager. This is represented by a NULL value in the manager column in the database.

Upvotes: 5

Related Questions