在sequelize.js测试脚本中有以下代码:
department.hasMany(employee,{as:'employees', foreignKey:'DepartamentoID'});
let prog = department.build({nombre:'Programming Dept.'});
let admin = department.build ({ nombre:'Administration'});
let maintenance = department.build( {nombre:'Maintenance'});
prog.save();
admin.save();
maintenance.save();
//create employees
const pepe = employee.build ({ nombre:'Pepe Gonzalez', posicion:'Manager'});
pepe.save();
const irma = employee.build ({ nombre:'Irma Pérez', posicion:'Office Hurricane'});
irma.save();
const ima = employee.build ({ nombre:'Ima Programmer', posicion:'Dev'});
ima.save();
prog.setEmployees([pepe,irma,ima]);
prog.save();
const juanito = employee.build ({ nombre:'Juanito Velez', posicion:'Manager'});
juanito.save();
const zoyla = employee.build ({ nombre:'Zoyla Gartija', posicion:'Dev'});
zoyla.save();
const gallu = employee.build ({ nombre:'Gallu el jíbaro', posicion:'Musician'});
gallu.save();
admin.setEmployees([juanito,zoyla,gallu]);
admin.save();
代码成功运行,并且所有记录都在目标数据库中创建,但是,Employees表的所有记录上的“ DepartamentoID”列均为空白。根据文档,当我创建hasMany关系时,会自动创建一个setter方法。我是在做错什么还是只是误读了文档?
答案 0 :(得分:0)
您将需要显式设置DepartamentoID
。例如:
let maintenance = department.build( {nombre:'Maintenance'});
maintenance.save();
//create employees
const pepe = employee.build ({
nombre:'Pepe Gonzalez',
posicion:'Manager',
DepartamentoID: maintenance.id
});
pepe.save();