Sequelize只获取自己的属性,忽略包含的实例



我要找的是Model中的一个实例方法,它只返回该模型的属性&排除任何包含模型的实例。

例如:想象一下,我有两个模型,有一个hasMany(或任何(关联:

Post {
id,
content,
user_id
}
User: {
id,
name,
}

我有:

const userWithPosts = await User.findOne({
where: { id: 33 },
include: [{
model: Post,
as: 'posts'
}]
});
console.log(userWithPosts)
/*
{
id: 33,
name: 'John Doe',
posts: [
Post {
id: 1,
content: '..',
user_id: 33
},
Post {
id: 2,
content: '...',
user_id: 33
}
]
}
*/

我正在寻找一种方法,比如getOwnAttributes或类似的方法:

userWithPosts.getOwnAttributes()
/*
{
id: 33,
name: 'John Doe',
}
*/

我研究了几件事:

userWithPosts.get({ raw: true })
userWithPosts.get({ plain: true })
userWithPosts.toJSON()

上述所有返回都包含实例
有任何现有的方法或变通方法可以做到这一点吗?

编辑:我不是说在查询时执行,而是从已经查询的实例中获取值。目前我的工作是:

const payload = _.pick(userWithPosts.toJSON(), [
...Object.keys(User.rawAttributes),
]);

您可以参考下面的代码来排除Post表的属性。

const userWithPosts = await User.findOne({
where: { id: 33 },
include: [{
model: Post,
as: 'posts',
attributes: []
}]
});

我希望它能有所帮助!

最新更新