我正在使用sequelize与数据库连接。 我已经关联了2个模型,但是当我得到这些模型时,它会向我显示错误。
这是我的模型代码
const Sequelize = require('sequelize');
const sequelize = require('../database/database');
const Purpose = sequelize.define('purpose', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
title: {
type: Sequelize.STRING,
allowNull: false
},
weighting: {
type: Sequelize.STRING,
allowNull: false
},
iconsUrl: {
type: Sequelize.STRING,
allowNull: false
}
})
module.exports = Purpose;
这是我将目的与其他表关联的方式
PurposeList.belongsToMany(User, { through: PurposeUser });
User.hasMany(LifeArea);
当我获取目的表或添加include: [ { model: PurposeUser, as: 'projects' } ],
时出现此错误purposeUser is not associated to purpose!
我正在Angular 7中使用它。
我不确定这是否与角度相关,或者我使用的东西有误。
exports.getUserPurpose = (req, res, next) => {
const userID = req.userData.userId;
const purposesList = [];
PurposeUser.findAll({ where: {userId: userID },
order: ['menuOrder'],
})
.then(results => {
const purposeID = [];
results.map(res => {
purposeID.unshift(res.dataValues.purposeId);
purposesList.unshift({id: res.dataValues.id, purposeId: res.dataValues.purposeId, weighting: res.dataValues.weighting})
});
return Purpose.findAll({
include: [ { model: PurposeUser, as: 'projects' } ],
where: {id: purposeID},
})
})
.catch(err => console.log('err', err));
}```
答案 0 :(得分:0)
您需要设置关系的两边...
Purpose.belongsToMany(User, { through: PurposeUser, as: 'Users', foreignKey: 'purpose_id' });
User.belongsToMany(, {Purpose, {through: PurposeUser, as: 'Purposes', foreignKey: 'user_id' });
您还需要在其中分配一些外键值,因为您可能已在PurposeUser中将列命名为Purpose_id和user_id。我看不到...