我到处都找过了,找不到任何明确的答案。 我有一个复杂的 findAll(),其中包含许多内容,每个内容都有自己的虚拟字段。 我想要的是修改结果的虚拟字段,但是当它返回试图访问虚拟字段的模型实例时返回未定义,因为它们不在结果中。 我已经尝试过“原始:真实”,但这会删除所有虚拟字段,并且由于我的数据有嵌套表,这些表也有自己需要的虚拟字段,所以我不能这样做。
示例模型
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;
});
关于javascript - 如何从 sequelize findAll 结果修改虚拟字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60843078/