繁体   English   中英

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

[英]Sequelize get own attributes only, ignore included instances

我正在寻找的是Model中的一个实例方法,它将仅返回该模型的属性并排除任何包含模型的实例。

例如:想象一下我有 2 个模型,具有hasMany (或 any )关联:

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: []
  }]
});

我希望它有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM