我对此相当陌生(使用 sequelize),一切对我来说都是新的。问题是我可以通过我的“users.model.js”创建和获取用户,但现在我想创建一个名为“data.model.js”的模型来将一些数据与某个用户相关联。
因此,根据 Sequelize 文档,我的关联应如下所示:
Users.hasMany(Data)
Data.belongsTo(Users)
但是当 sequelize 创建我的表时,我的数据表中没有我的外键。
我将与您分享我的代码:
配置文件(config.js):
const Sequelize = require('sequelize');
const connection = new Sequelize('drglicemia', 'root', '', {
host: 'localhost',
dialect: 'mysql'
});
module.exports = connection;
数据模型.js:
const sequelize = require('sequelize');
const db = require('../config/database');
const usersTable = require('./users.model')
let Data = db.define('tabeladados', {
dta: { type: sequelize.DATEONLY },
hora: { type: sequelize.DATE },
indiceglicemia: { type: sequelize.STRING },
insulina: { type: sequelize.STRING },
medicacao: { type: sequelize.STRING },
}, {
timeStamps: false, tableName: 'tabeladados'
});
//associates the dataTable table with the users
Data.associate = () => {
Data.belongsTo(usersTable)
}
module.exports = Data;
users.model.js:
const sequelize = require('sequelize');
const promise = require('bluebird')
const bcrypt = promise.promisifyAll(require('bcrypt'))
const db = require('../config/database');
const dataTable = require('./data.model')
let Users = db.define('utilizadores', {
username: { type: sequelize.STRING },
email: { type: sequelize.STRING },
password: { type: sequelize.STRING },
}, {
timeStamps: false, tableName: 'utilizadores',
});
//encrypts the password before submiting to the database
Users.beforeCreate((user, options) => {
return bcrypt.hash(user.password, 10)
.then(hash => {
user.password = hash;
})
.catch(err => {
throw new Error();
});
});
//validates the password submited by the user with the one encrypted in the database
Users.prototype.validPassword = async (password) => {
return await bcrypt.compare(password, this.password);
}
//associates the users table with the dataTable
Users.associate = () => {
Users.hasMany(dataTable)
}
module.exports = Users;
我相信,当我试图关联我的表时,我做错了什么,因为我觉得我做错了。
我不知道,但除此之外一切正常。
但是就像我一开始说的,我是 Sequelize xD的新手
最佳答案
我认为原因是 循环引用 。 user.model.js
需要 data.model.js
, data.model.js
需要 user.model.js
。
您需要创建一个 index.js
文件。要求并在此处为所有模型建立关联,然后重新导出它们。例如。./models/index.js
:
const User = require('./user.model.js');
const Data = require('./data.model.js');
User.hasMany(Data);
Data.belongsTo(User);
module.exports = {User, Data}
service.js
或 controller.js
:const models = require('./models/index.js');
// use models
await models.User.findAll();
删除模型文件中的以下代码:
// Remove from user.model.js file
Users.associate = () => {
Users.hasMany(dataTable)
}
// Remove from data.model.js file
Data.associate = () => {
Data.belongsTo(usersTable)
}
关于javascript - Sequelize 两个表之间的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61257195/