簡體   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