[英]sequelize hasMany, how to use customized foreginKey
Model EmployeeView 模型EmployeeView
module.exports = function(sequelize, DataTypes) {
var _this = sequelize.define('EmployeeView', {
employeeId: {
type: DataTypes.INTEGER,
field: 'code'
},
username: DataTypes.STRING,
email: {
type: DataTypes.STRING,
field: 'emailaddress'
},
department: {
type: DataTypes.STRING,
field: 'department_name'
},
departmentId: {
type: DataTypes.STRING,
field: 'departments_id'
}
}, {
timestamps: false,
freezeTableName: true,
tableName: 'employees_view',
classMethods: {
associate: function(models) {
_this.belongsTo(models.EmployeeCategory, {
foreignKey: {
name: 'employeecategories_id'
}
});
_this.hasMany(models.EmployeeFile, {
foreignKey: 'employees_code'
});
}
}
});
return _this;
};
Model EmployeeFile 模型EmployeeFile
module.exports = function(sequelize, DataTypes) {
var _this = sequelize.define("EmployeeFile", {
employeeId: {
type: DataTypes.INTEGER,
field: 'employees_code'
},
filename: {
type: DataTypes.STRING,
filed: 'filename'
},
employeeFileTypeId: {
type: DataTypes.INTEGER,
field: 'employee_file_types_id'
}
}, {
timestamps: false,
freezeTableName: true,
tableName: 'employee_files'
});
return _this;
};
Router 路由器
router.get('/employee', function(req, res) {
models.EmployeeView.findAll({
where: {
active: req.query.active
}
include: [{
model: models.EmployeeCategory
}, {
model: models.EmployeeFile,
}]
}).then(function(employee) {
res.json(employee);
});
});
I have two tables ' employee_view ' ( it is a view ) and ' employee_files ' which map to the ' EmployeeView ' and ' EmployeeFile '. 我有两个表' employee_view '( 它是一个视图 )和' employee_files ',它们映射到' EmployeeView '和' EmployeeFile '。 ' employee_view ' has ' id ' field as the primary key and ' code ' field as the employee number.'
' employee_view '将' id '字段作为主键,将' code '字段作为员工编号。 employee_files ' has ' employees_code ' as its primary key and foreignKey which bindings with the ' code ' field.
employee_files '有' employees_code '作为主键,foreignKey与' code '字段绑定。 So I want to get ' employee_files ' data through this relation.
所以我希望通过这种关系得到' employee_files '数据。
Actually,I got nothing. 实际上,我一无所获。 Because the sequelize will execute "EmployeeView.id == EmployeeFile.employees_code".
因为sequelize将执行“EmployeeView.id == EmployeeFile.employees_code”。 But I want the sequelize to execute "EmployeeView.code == EmployeeFile.employees_code" .What should I do?
但我希望sequelize执行“EmployeeView.code == EmployeeFile.employees_code”。我该怎么办?
just add primaryKey: true
to your employeeId field to link the EmployeeView to EmployeeFiles since the belongsToMany relationship will only link to the primary key of it's parent 只需将
primaryKey: true
添加到employeeId字段即可将EmployeeView链接到EmployeeFiles,因为belongsToMany关系只链接到它的父级的主键
employeeId: {
type: sequelize.INTEGER,
field: 'code',
primaryKey: true
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.