我正在使用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()
这会导致所有员工被删除。我是否设置了错误的关系?
答案 0 :(得分:1)
当我使用控制台插件运行此代码时:
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()
DB的结果状态(第一个添加的员工被删除):
EMPLOYEE
ID VERSION
1 1
2 0
3 0
STORE
ID VERSION
1 2
STORE_EMPLOYEES
EMPLOYEE_ID STORE_ID
2 1
3 1