Sequelize中的助理未按预期工作

时间:2019-06-23 15:18:13

标签: javascript node.js postgresql express sequelize.js

我正在尝试在Sequelize中关联两个表,但是我遇到了SequelizeEagerLoadingError,尽管尝试了该平台上的所有可用修补程序,但一个表并未与另一个表关联。

我有两个表,User和Item。

用户(user.js)

const User = dbconnection.sequelize.define('users', {
    id:  { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
    name: {
        type:  Sequelize.STRING(80),
        allowNull: false
    },
    email: {
        type:  Sequelize.STRING(120),
        allowNull: false,
        unique: true
    },
    dob: {
        type: Sequelize.DATEONLY,
        allowNull: false
    },
    password: {
        type:  Sequelize.STRING(256),
        allowNull: false
    }

});

User.associate = models => {
    User.hasMany(models.Item, { as: 'items',foreignKey: 'user_id' })
}

dbconnection.sequelize.sync({ force: false })
    .then(() => {
        //console.log('Table created!')
    });

module.exports = {
    User
};

项目(item.js)

const Item = dbconnection.sequelize.define('items', {
    id:  { type: Sequelize.INTEGER, unique: true, autoIncrement: true, primaryKey: true},
    item: {
        type: Sequelize.STRING(80),
        allowNull: true
    },
    item_type: {
        type: Sequelize.STRING(10),
        allowNull: false
    },
    comment: {
        type: Sequelize.STRING(1000),
        allowNull: true
    },
    user_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'users', key: 'id' }
    },
});

Item.associate = models => {
    Item.belongsTo(models.User, { as: 'users',foreignKey: 'user_id' })
}

dbconnection.sequelize.sync({ force: false })
    .then(() => {
        // console.log('Table created!')
    })
});

module.exports = {
    Item
};

用户hasMany(Item),而项目属于(用户),如上所示。

但是,当我查询Item表(如下所示)时,

const usersdb = require('./userdb')
const itemsdb = require('./itemdb')

class ItemsController {
    static async getAllItems(req, res, next) {
        try{
            let allitems = await itemsdb.Item.findAll({
                include: [{
                    model: usersdb.User
                }]
            })
            return {items: allitems, status: true}
        }
        catch (e) {
            return {items: e, status: false}
        }
    }
}

module.exports = ItemsController;

我收到SequelizeEagerLoadingError,该错误是“用户未与项目关联!”

我尝试了所有可用的修复程序,包括thisthis等,但都没有成功。

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方法。首先,我删除了表并丢弃了模型定义。其次,我使用sequelize model:create --name ModelName --attributes columnName:columnType命令生成了迁移和模型。然后,就像我之前所做的那样,我使用生成的模型将两个表关联起来。最后,我运行了sequelize db:migrate命令来创建表,并在运行查询时成功了!

以前,我是手动创建模型的。加载模型后,我还使用sequelize.sync({force: false/true})命令创建了表。

用户模型(user.js)

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    email: {
        type:  DataTypes(120),
        allowNull: false,
        unique: true
    },
    dob: {
        type: DataTypes.DATEONLY,
        allowNull: false
    },
    password: {
        type:  DataTypes.STRING(256),
        allowNull: false
    }
  }, {});
  User.associate = function(models) {
    User.hasMany(models.Item, {as: 'Item', foreignKey: 'user_id'})
  };
  return User;
};

项目模型(item.js)

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Item = sequelize.define('Item', {
    item: {
      type: DataTypes.STRING(80),
      allowNull: true
    },
    item_type: {
      type: DataTypes.STRING(10),
      allowNull: false
    },
    comment: {
      type: DataTypes.STRING(1000),
      allowNull: true
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: 'User', key: 'id' }
    }
  }, {});
  Item.associate = function(models) {
    Item.belongsTo(models.User, { as: 'User',foreignKey: 'user_id' })
  };
  return Item;
};

查询(queryitem.js)

const Item = require('../models').Item
const User = require('../models').User

class ItemsController {
    static async getAllItems() {
        try{
            let allitems = await Item.findAll({
                include: [{
                    model: User,
                    as: 'User'
                }]
            })
            return {items: allitems, status: true}
        }
        catch (e) {
            return {items: e, status: false}
        }
    }
}

module.exports = ItemsController;