这是我参与11月更文挑战的第21天,活动详情查看:2021最后一次更文挑战
模型查询-查找器(find)
select查询结果返回是模型类的实例,Sequelize会自动将所有内容包裹返回实例对象中.,如果不想要这些信息,请将 { raw: true } 作为参数传递给 find 方法.
findByPk
findByPk 方法使用提供的主键从表中得到一条记录.
const project = await Project.findByPk(1);
if (project === null) {
console.log('Not found!');
} else {
console.log(project instanceof Project); // true
// 它的主键是 1
}
findOrCreate
findOrCreate当根据条件未找到该记录时,将会自动创建一条记录,并返回实例和一个布尔值,指示是已创建还是已经存在.
使用 where 参数来查找记录,而使用 defaults 参数来定义必须创建的内容. 如果 defaults 不包含每一列的值,则 Sequelize 将采用 where 的值(如果存在)
const [user, created] = await User.findOrCreate({
where: { name: '李华' },
defaults: {
age: 18
}
});
console.log(user.name); // '李华'
console.log(user.age); // 这可能是也可能不是 '18'
console.log(created); // 指示此实例是否刚刚创建的布尔值
if (created) {
console.log(user.age); // 这里肯定是 '18'
}
findAndCountAll
findAndCountAll 方法是结合了 findAll 和 count 的参数的方法. 一般在处理与分页有关的查询时,会非常有用,在分页中,想检索带有 limit 和 offset 的数据,但有需要知道与查询匹配的记录总数.
findAndCountAll 方法返回一个具有两个属性的对象:
count- 一个整数 - 符合查询条件的记录总数rows- 一个数组对象 - 获得的记录
const { count, rows } = await Project.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
});
console.log(count);
console.log(rows);
获取器
是模型中的定义的 get() 函数:
const User = sequelize.define('user', {
// 假设我们想要以大写形式查看每个用户名,
// 即使它们在数据库本身中不一定是大写的
username: {
type: DataTypes.STRING,
get() {
const rawValue = this.getDataValue('username');
return rawValue ? rawValue.toUpperCase() : null;
}
}
});
在读取字段值时会自动调用此获取器:
const user = User.build({ username: 'abc' });
console.log(user.username); // 'ABC'
console.log(user.getDataValue('username')); // 'abc'
真正存储在数据库中的值是 abc,但是返回 ABC,使用了 this.getDataValue('username') 来获得该值,并将转换为大写.