【问题标题】:How to use findAll with associations in Sequelize如何在 Sequelize 中将 findAll 与关联一起使用
【发布时间】:2020-01-01 00:18:56
【问题描述】:

我在将 findAll() 方法与 Sequelize 的关联一起使用时遇到问题。 我有两个模型:帖子和作者(一个作者有很多帖子,一个帖子有一个作者),我用 Sequelize-cli 创建,然后通过迁移命令npx sequelize db migrate:all 我在 mysql 中创建了它们。为了使事情井井有条,我在另一个迁移文件中拥有模型之间的关联(使用npx sequelize init:migrations 创建,毕竟所有模型都已经存在),所以我的代码如下所示:

作者模型

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Author = sequelize.define('Author', {
    authorName: { 
      type: DataTypes.STRING,
      validate: {
        is: ["^[a-z]+$",'i'], 
      }
    },
    biography: {
      type: DataTypes.TEXT,
      validate: {
        notEmpty: true,
      }
    }
  }, {});
  Author.associate = function(models) {
    Author.hasMany(models.Post);
  };
  return Author;
};

发布模型

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    title: { 
      type: DataTypes.STRING,
      validate: {
        is: ["^[a-z]+$",'i'],
        notEmpty: true,
      },
    },
    content: { 
      type: DataTypes.TEXT,
      validate: {
        notEmpty: true,
      },
    },
    likes: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      validate: {
        isInt: true,  
      },
    },
  }, {});
  Post.associate = function(models) {
    // associations can be defined here
  };
  return Post;
};

关联文件(迁移)(仅显示重要的部分)

up: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.transaction(t => {
      return Promise.all([
        queryInterface.addColumn('Posts','AuthorId', {
            type: Sequelize.INTEGER,
            references: {
              model: 'Authors',
              key: 'id',
            },
            onUpdate: 'CASCADE',
            onDelete: 'SET NULL',
        }, { transaction: t }),
        queryInterface.addColumn('Posts', 'ImagesId', {
            type: Sequelize.INTEGER,
            references: {
              model: 'Images',
              key: 'id',
            },
            onUpdate: 'CASCADE',
            onDelete: 'SET NULL',
        }, { transaction: t }),
        queryInterface.addColumn('Posts', 'CategoryId', {
          type: Sequelize.INTEGER,
          references: {
            model: 'Categories',
            key: 'id',
          },
          onUpdate: 'CASCADE',
          onDelete: 'SET NULL',
        }, { transaction: t }),
      ]);
    });

这显然工作正常,因为在 Mysql-Workbench 中它向我显示以下内容:

但是,当我尝试像这样使用findAll() 时:

const { Post, Author } = require('../models/index');

function(response) {
   Post.findAll({ 
      attributes: ['id', 'title', 'content', 'likes'],
      include: {
        model: Author,
      }
   })
   .then(result => response.json(result))
     .catch(error => response.send(`Error getting data. Error: ${error}`));

它给了我以下error

SequelizeEagerLoadingError: Author is not associated to Post!

所以,我不知道如何继续了。我一直在尝试许多其他方法,但都没有成功。我已经在 StackOverFlow 中阅读了许多其他关于如何解决此类问题的问题,但这些问题也没有成功。

提前致谢。

【问题讨论】:

    标签: mysql node.js sequelize.js sequelize-cli


    【解决方案1】:

    在查询 Post 模型时,您还需要定义 Post 的关联

    Post.associate = function(models) {
      Post.belongsTo((models.Author);
    };
    

    你需要从两端添加一个关联 Post -> AuthorAuthor -> Post ,这样你就永远不会陷入这种错误。

    【讨论】:

    • 谢谢!那么,如果我在帖子和类别之间有关系,例如,我是否也需要显式调用它?我认为只有一种关联方法就足够了
    【解决方案2】:

    总结this documentation我们有以下几点:

    如果您有这些型号:

    const User = sequelize.define('user', { name: DataTypes.STRING });
    const Task = sequelize.define('task', { name: DataTypes.STRING });
    

    它们是这样关联的:

    User.hasMany(Task);
    Task.belongsTo(User);
    

    您可以通过以下方式获取它们及其关联元素:

    const tasks = await Task.findAll({ include: User });
    

    输出:

    [{
      "name": "A Task",
      "id": 1,
      "userId": 1,
      "user": {
        "name": "John Doe",
        "id": 1
      }
    }]
    

    const users = await User.findAll({ include: Task });
    

    输出:

    [{
      "name": "John Doe",
      "id": 1,
      "tasks": [{
        "name": "A Task",
        "id": 1,
        "userId": 1
      }]
    }]
    

    【讨论】:

      猜你喜欢
      • 2019-12-27
      • 1970-01-01
      • 2017-05-19
      • 2013-10-22
      • 2018-10-23
      • 2016-03-28
      • 2017-08-23
      • 2015-11-09
      • 1970-01-01
      相关资源
      最近更新 更多