[英]Sequelize get own attributes only, ignore included instances
What I'm looking for is an instance method in Model
that will return only the attributes of that model & exclude instances of any included model.我正在寻找的是
Model
中的一个实例方法,它将仅返回该模型的属性并排除任何包含模型的实例。
eg: Imagine I have 2 models, with a hasMany
( or any ) association:例如:想象一下我有 2 个模型,具有
hasMany
(或 any )关联:
Post {
id,
content,
user_id
}
User: {
id,
name,
}
and I have:我有:
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
}
]
}
*/
I'm looking for a method, say getOwnAttributes
or something like that which does:我正在寻找一种方法,比如
getOwnAttributes
或类似的方法:
userWithPosts.getOwnAttributes()
/*
{
id: 33,
name: 'John Doe',
}
*/
I've looked into couple of things:我研究了几件事:
userWithPosts.get({ raw: true })
userWithPosts.get({ plain: true })
userWithPosts.toJSON()
All of the above returns included instances as well.以上所有返回也包括实例。
Any existing method or workaround that can do this?任何现有的方法或解决方法可以做到这一点?
EDIT: I'm not talking about doing it at query time, but getting the value from already queried instance.编辑:我不是在谈论在查询时执行它,而是从已经查询的实例中获取值。 Currently my work-around for this is:
目前我的解决方法是:
const payload = _.pick(userWithPosts.toJSON(), [
...Object.keys(User.rawAttributes),
]);
You can refer to the code below to exclude attributes of Post
table.您可以参考下面的代码来排除
Post
表的属性。
const userWithPosts = await User.findOne({
where: { id: 33 },
include: [{
model: Post,
as: 'posts',
attributes: []
}]
});
I hope it helps!我希望它有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.