我正在使用sequelize在我的node.js项目中创建一个数据库。到目前为止,我只使用了beforeTo和hasOne,它们运行良好。但是,现在我需要创建多对多关系,我有点困惑,后遗症无法正确地使用“槽”属性解释我的belongsToMany。任何帮助,将不胜感激。干杯!
定义所有关系的索引文件
const express = require('express');
const app = express();
const sequelize = require('./db/database');
const User = require('./models/User');
const Tenant = require('./models/Tenant');
const Role = require('./models/Role');
const Class = require('./models/Class');
const Level = require('./models/Level');
const Subject = require('./models/Subject');
const Student = require('./models/Student');
const Contact = require('./models/Contact');
const StudentContact = require('./models/StudentContact');
const userRoutes = require('./routes/user');
const authRoutes = require('./routes/auth');
const tenantRoutes = require('./routes/tenant');
const seed = require('./db/seed');
const port = process.env.PORT || 8080;
// allows node to parse querystrings
app.use(express.json({ extended: false }));
// routes for our endpoints
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/tenant', tenantRoutes);
// sets up the role and tenant relationships to the user.
User.belongsTo(Tenant, { foreignKey: { allowNull: false } });
User.belongsTo(Role, { foreignKey: { allowNull: false } });
Class.belongsTo(Level, { foreignKey: { allowNull: false } });
Class.belongsTo(Tenant, { foreignKey: { allowNull: false } });
Class.belongsTo(Subject, { foreignKey: { allowNull: false } });
Student.belongsTo(Class, { foreignKey: { allowNull: false } });
Student.belongsToMany(Contact, {
as: 'Contacts',
through: { model: StudentContact, unique: false },
foreignKey: 'student_studentId'
});
Contact.belongsToMany(Student, {
as: 'Students',
through: { model: StudentContact, unique: false },
foreignKey: 'contact_contactId'
});
sequelize
.sync({ force: true })
.then(result => {
return Tenant.findByPk(1);
})
.then(tenant => {
if (!tenant) {
seed();
}
app.listen(port, () =>
console.log(`Example app listening on port ${port}!`)
);
})
.catch(err => console.log(err));
app.get('/', (req, res) => {
sequelize
.authenticate()
.then(() => {
res.send(`Hello World! Connection has been established successfully.`);
})
.catch(err => {
res.send(`Hello World! 'Unable to connect to the database:' ${err}`);
});
});
我的学生模型:
const Sequelize = require('sequelize');
const sequelize = require('../db/database');
const Students = sequelize.define('student', {
studentId: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
}
});
module.exports = Students;
我的联系人模型:
const Sequelize = require('sequelize');
const sequelize = require('../db/database');
const Contacts = sequelize.define('contact', {
contactId: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
}
});
module.exports = Contacts;
我的StudentContact模型:
const Sequelize = require('sequelize');
const sequelize = require('../db/database');
const StudentContact = sequelize.define('studentContact', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
}
});
module.exports = StudentContact;
我也尝试手动设置FK,但也无济于事。 Sequelize的文档仅告诉我使用BelongsToMany,但显然还有更多内容。
https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
答案 0 :(得分:1)
不久前,我遇到了类似的问题,也很沮丧,无法从续集文档中找到正确的解决方案。后来,我解决了一个不是最好的解决方案,但对我来说很好用。 在StudentContact模型中手动设置两个FK后,可以编写以下两个语句。
StudentContact.belongsTo(Students,{foreignKey:“ id”})
StudentContact.belongsTo(Contacts,{ForeignKey:“ id”});
答案 1 :(得分:1)
您只需要像下面这样更改StudentContact的定义:
dopri5