【发布时间】: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