tags:

views:

261

answers:

1

I'm using Grails 1.2 and have the following many-to-many relationship setup:

class Employee {
    static belongsTo = Store
    static hasMany = [stores:Store]
}

class Store {
    static hasMany = [employees:Employee]
}

I seed some data in Bootstrap.groovy:

store1.addToEmployees(employee1).save()
store1.addToEmployees(employee2).save()
store1.addToEmployees(employee3).save()

This results in the following DB data:

| store_employees | 
----------------------------------
| store_id        | employee_id   |
|    1            | 1             | 
|    1            | 2             |
|    1            | 3             |
----------------------------------

Next, I try to remove a single employee from the store:

store.removeFromEmployees(employee1).save()

This results in all employees getting removed. Did I setup the relationship wrong or something?

A: 

Hmm, I am not getting the same issue.

When I run this code using console plugin:

Store.list()*.delete() //clear so you can run script multiple times
Employee.list()*.delete()   //clear so you can run script multiple times

store1 = new Store().save()
 employee1 = new Employee()
 employee2 = new Employee()
 employee3 = new Employee()

store1.addToEmployees(employee1).save()
store1.addToEmployees(employee2).save()
store1.addToEmployees(employee3).save(flush:true)


Store.list()[0].removeFromEmployees(Employee.list()[0]).save()

The resulting state of DB (first added employee was removed):

EMPLOYEE
ID  VERSION
1   1
2   0
3   0

STORE
ID  VERSION
1   2

STORE_EMPLOYEES
EMPLOYEE_ID     STORE_ID
2   1
3   1
Jean Barmash
I didn't use the console but wrote the code in Bootstrap and an integration test. Could not reproduce the problem. Grails 1.2
Michael Easter