根据doc
如果选项.raw
If set to true, field and virtual setters will be ignored
但是字段和虚拟 setter 的含义是什么?
我看过很多网站,但似乎没有关于当 options.raw
的值为 true/false 时查询结果格式的示例。
假设我在 Sequelize 中创建了 users
模型
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
const db = require('../sequelize')
let users = db.define('users', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: 'email'
},
password: {
type: DataTypes.STRING,
},
},
{
hooks: {
beforeCount(options) {
options.raw = true; // what would be the difference when I set it to false
}
}
}
);
users.sync().then(() => {
console.log('user table created');
});
module.exports = users;
当我将 options.raw
设置为 false 时会有什么不同?
有什么例子吗?
最佳答案
In its most basic form set will update a value stored in the underlying dataValues object. However, if a custom setter function is defined for the key, that function will be called instead. To bypass the setter, you can pass raw: true in the options object.
如果 raw 为 true,自定义 getter 和 setter 将被忽略。
require('sqlite3');
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:')
const User = sequelize.define('User', {
firstName: {
type: DataTypes.STRING,
get() {
return this.getDataValue('firstName').toUpperCase()
}
},
lastName: {
type: DataTypes.STRING,
set(value) {
this.setDataValue('lastName', value + '--------');
}
}
});
let user = User.build({ firstName: 'John', lastName: 'Doe' });
console.log(user.lastName); // Doe--------
console.log(user.get()) // {firstName: "JOHN", id: null, lastName: "Doe--------"}
user = User.build({ firstName: 'John', lastName: 'Doe' }, {raw: true});
console.log(user.lastName); // Doe
console.log(user.get({raw: true})) // {firstName: "John", id: null, lastName: "Doe"}
关于mysql - Sequelize - 原始 :true and raw:false 和有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67530074/