在创建帖子时,Sequlelize不返回关联的用户。这是路由器。
我也参考了文档。
https://sequelize.org/master/manual/associations.html#creating-with-associations
createPost: async (req: any, res: Response) => {
const postData = {
title: req.body.title,
postContent: req.body.postContent,
authorId: req.session.user.id
};
await models.Post.create(postData, {
include: [{ model: models.User, as: "author" }]
})
.then(post => {
res.status(200).send({
message: "post created",
post: post
});
})
.catch(err => {
res.status(401).send({
message: `Something went wrong`,
error: err
});
});
console.log(req.body);
}
我不确定为什么这行不通,因为这条路线是使用相应用户名和用户名发帖的
getPosts: async (req: Request, res: Response) => {
await models.Post.findAll({
include: [
{ model: models.User, as: "author", attributes: ["username"] },
{ model: models.Likes }
],
order: [["createdAt", "DESC"]],
limit: 6
}).then(posts => {
res.json(posts);
});
},
这是发布和用户模型。
User.js
"use strict";
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define("User", {
username: DataTypes.STRING,
password: DataTypes.STRING,
email: DataTypes.STRING,
forget_password: DataTypes.STRING
});
User.associate = function (models) {
User.hasMany(models.Post, {
foreignKey: "authorId",
as: "author",
onDelete: "CASCADE"
});
};
return User;
};
Post.js
"use strict";
module.exports = (sequelize, DataTypes) => {
var Post = sequelize.define("Post", {
title: DataTypes.STRING,
postContent: DataTypes.STRING,
liked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
likeCounts: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
},
authorId: DataTypes.INTEGER
});
Post.associate = function (models) {
Post.belongsTo(models.User, {
as: "author",
foreignKey: "authorId",
onDelete: "CASCADE"
});
Post.hasMany(models.Likes, {
foreignKey: "resourceId",
timestamps: false,
onDelete: "CASCADE",
scope: {
type: "article"
}
});
};
return Post;
};
答案 0 :(得分:0)
这给了我想要的结果,所以它将起作用。
await models.Post.create(postData)
.then(post => {
models.Post.findOne({
where: {
id: post.id
},
include: [
{ model: models.User, as: "author", attributes: ["username"] },
{ model: models.Likes }
]
}).then(newPost => {
res.status(200).send({
message: "post created",
post: newPost
});
});
})