[英]How to query associated models in Node/Postgres
我正在用Express構建一個應用程序,並且正在使用postgres和sequelize進行ORM。 我有兩個模型, User
和Post
。
在我的user.js
和post.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' });
我正在嘗試呈現用戶完成的所有帖子,但可能丟失了一些內容。
在我的路線中,我可以找到正確的用戶,但我不知道如何進行。
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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.