mysql - 如何在 Sequelize 中使用 findAll 和关联

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

我在使用带有 Sequelize 关联的 findAll() 方法时遇到问题。 我有两个模型:帖子和作者(一个作者有很多帖子,一个帖子有一个作者),我用 Sequelize-cli 创建了它们,然后通过迁移命令 npx Sequelize db migrate:all i已在 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 中它向我显示了以下内容:forget about the images and categories

但是,当我尝试使用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 中阅读了许多有关如何解决此类问题的其他问题,但这些问题也没有成功。

提前致谢。

最佳答案

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

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

您需要从两端添加关联, Post -> AuthorAuthor -> Post ,这样您就永远不会陷入此类错误。

关于mysql - 如何在 Sequelize 中使用 findAll 和关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57681084/

相关文章:

mysql - VIEW 中的 SQL 多个 SELECT 语句

mysql - 我可以在 mysql 中创建一个 ID 来自动递增,例如 't00000000' 吗?

php - Typo3 $this->cObj->enableFields() SQL 错误 WHERE AND

node.js - 将 React + Express 应用程序部署到 Kubernetes。如何用docker构建它?

mysql - MySQL表中的created_At字段可以编辑吗?

node.js - 序列化关联不创建外键

mysql group by query with column filter

node.js - 在我的 Node.js 应用程序中的什么地方初始化我的 Firebase 实例?

node.js - 如何在查询运行时将属性与 dynamodb 表 -> 项目 -> 属性中的小写值进行比较

javascript - 传递给 queryInterface.removeConstraint() 的选项对象的属性是什么?