序列化包含不适用于关联表

时间:2019-12-28 15:18:06

标签: node.js model include sequelize.js associations

我正在使用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.
  • 我尝试在用户模型中使用hasOne而不是hasMany-不变
  • 我在用户模型中尝试了hasMany,并删除了消息模型的belongsTo-不变
  • 我在消息模型中尝试了belongsTo,并删除了用户模型的hasMany-不变
  • 我删除了所有表格并重试了所有内容-不变

我在做什么错了?

1 个答案:

答案 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
        });
    });
};