我正在使用sequelize 5.21.2
我有一个用户模型:
'use strict';
module.exports = (sequelize, Sequelize) => {
const users = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
firstname: {
type: Sequelize.STRING,
allowNull: false,
},{
timestamp: true,
logging: console.log,
});
users.associate = function(models) {
models.users.hasMany(models.messages);
};
return users;
};
消息模型:
'use strict';
module.exports = (sequelize, Sequelize) => {
const messages = sequelize.define('messages', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
message:{
type: Sequelize.TEXT,
allowNull: false
}
}, {
timestamp: true,
logging: console.log,
scopes:{
withUser:{
include: [
{
model: sequelize.models.users
}
]
}
}
});
messages.associate = function(models) {
models.messages.belongsTo(models.users);
};
return messages;
};
我的控制器:
const db = require('../models');
const Messages = db.messages
exports.getOneMessage = (req, res) =>{
Messages.scope(['withUser']).findByPk(req.query.id).then(message => {
res.status(200).json({
"description": "getOne - " + req.query.id,
"message": message
});
}).catch(err => {
res.status(500).json({
"description": "Can not access",
"error": err
});
});
};
我遇到此错误:
Error: Include unexpected. Element has to be either a Model, an Association or an object.
我在做什么错了?
答案 0 :(得分:0)
问题似乎出在范围... 如果我将自己包含在控制器中,则一切正确。 我在项目中使用了很多范围,但是唯一引起麻烦的是用户模型...我不知道为什么。
const db = require('../models');
const Messages = db.messages
const Users = db.users
exports.getOneMessage = (req, res) =>{
Messages.findByPk(req.query.id, {include:[Users]}).then(message => {
res.status(200).json({
"description": "getOne - " + req.query.id,
"message": message
});
}).catch(err => {
res.status(500).json({
"description": "Can not access",
"error": err
});
});
};