我有两个表,分别称为“ employees”和“ employee_detail”。
我想对这两个表使用关系。我想使用belongsTo连接它。我已经遵循了一些教程,但是我无法做到。
任何人都可以帮助我。
exports.getEmployee = function(req, res) {
db.employs.findAll({
include: [
{
models: db.employ_detail
}
]
})}
.then(function(employs){
const resObj = employs.map(function(employs) {
//tidy up the employs data
return Object.assign(
{},
{
id: employs.id,
name: employs.name,
department: employs.department,
salary: employs.salary.map(function(employ_detail) {
//tidy up the post data
return Object.assign(
{},
{
id: employ_detail.id,
emp_id: employ_detail.emp_id,
name: employ_detail.name,
phone: employ_detail.phone
}
)
})
});
});
res.json(resObj)
});
这是我的db.js文件。
'use strict';
var Sequelize=require('sequelize');
var path=require('path');
var sequelize =new Sequelize('company', 'root', 'welcome123$', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.employs = require(path.resolve('./models/employee'))(sequelize, Sequelize);
db.employ_detail = require(path.resolve('./models/employ_detail.js'))(sequelize, Sequelize);
//Relations
db.employ_detail.belongsTo(db.employs);
//db.employs.hasMany(db.staffs);
module.exports = db;
答案 0 :(得分:0)
需要使用选项。
示例:
model.belongsTo(DIR.OrganizationModel, {
foreignKey: 'organization_id',
targetKey: 'organization_id',
constraints: false,
});
http://docs.sequelizejs.com/class/lib/associations/belongs-to.js~BelongsTo.html