1

我正在使用 Grails 1.2 并具有以下多对多关系设置:

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

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

我在 Bootstrap.groovy 中播种了一些数据:

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

这会产生以下数据库数据:

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

接下来,我尝试从商店中移除一名员工:

store.removeFromEmployees(employee1).save()

这导致所有员工都被解雇。我是否设置了错误的关系或什么?

4

1 回答 1

1

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
于 2010-01-09T03:47:28.087 回答