gpt4 book ai didi

node.js - 如何在 Node/Postgres 中查询关联模型

转载 作者:行者123 更新时间:2023-12-03 22:27:50 25 4
gpt4 key购买 nike

我正在用 express 构建一个应用程序,我正在为 ORM 使用 postgres 和 sequelize。我有两个模型, UserPost

在我的 user.jspost.js 文件中,我有:

module.exports = function(sequelize, DataTypes) {
return sequelize.define('users', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ""
},

module.exports = function(sequelize, DataTypes) {
return sequelize.define('posts', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER,
allowNull: true
},
title: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: ""
},

我导入了这两个模型,并进行了以下关联:
User.hasMany(Post, { foreignKey: 'user_id' });

Post.belongsTo(User, { foreignKey: 'user_id' });

我正在尝试呈现用户完成的所有帖子,但我可能遗漏了一些东西。

在我的 route ,我可以获得正确的用户,但我不知道如何继续。
router.route('/:id').get(async (req, res) => {
const user = await User.findById(req.params.id);
console.log(user);
res.send(user);
})

谢谢!

最佳答案

findById 不支持关联模型,

User.findById(req.params.id);

您可以将 findById 更改为 findOne 并包含这样的模型,
User.findOne({
where : { id : req.params.id },
include : {
model : Post
}
});

关于node.js - 如何在 Node/Postgres 中查询关联模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49790166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com