繁体   English   中英

如何从 sequelize findAll 结果修改虚拟字段?

[英]How to modify virtual fields from sequelize findAll result?

我到处找,找不到任何明确的答案。 我有一个复杂的 findAll() ,其中包含许多内容,每个内容都有自己的虚拟字段。 我想要的是修改结果的虚拟字段,但是当它返回试图访问虚拟字段的模型实例时,返回 undefined 因为它们还没有出现在结果中。 我尝试过 'raw: true' 但这会删除所有虚拟字段,并且由于我的数据具有嵌套表,这些表也有我需要的自己的虚拟字段,我不能这样做。

示例模型

var Book = sequelize.define('Book', {

        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        title: {
            type: DataTypes.STRING
        },
        author: {
            type: DataTypes.STRING
        }
        //....other columns,
        myField: {
            type: DataTypes.Virtual,
            get() {
                return this.getDataValue('title:') + this.getDataValue('author');
    })

获取数据

model.Book.findAll({
  limit: 100
})
.then((result) => {

  const newBook = result.map(row => {
    return {...row, myField: 'setMyOwnValueHere'}
  }

  return newBook
}

先获取模型数据: get

model.Book.findAll({
    limit: 100
}).then(result => {
    const books = result.map(row => {
        //this returns all values of the instance, 
        //also invoking virtual getters
        const book = row.get();
        book.myField = 'setMyOwnValueHere';
        return book;
    });
    return books;
});

暂无
暂无

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

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