Sequelize add, delete, modify and check
1 increasecreate
1.1 build
+ save
const xiaoxu = User.build({
name: "小徐" });
console.log(xiaoxu instanceof User); // true
console.log(xiaoxu.name); // "小徐"
// build 方法仅创建一个对象,该对象表示可以映射到数据库的数据,并没有与数据库通信
await xiaoxu.save();// 使用 save 方法,将这个实例真正保存到数据库中。
1.2 create
create
method, which combines the above build and save into one method.
const res = await User.create({
name: "小徐" });
1.3 bulkCreate
bulkCreate
Batch creation, the received parameter is an array object.
const captains = await Captain.bulkCreate(
[
{
name: '小徐' },
{
name: '小明' }
]
);
console.log(captains.length); // 2
console.log(captains[0] instanceof Captain); // true
console.log(captains[0].name); // '小徐'
console.log(captains[0].id); // 1 // (或另一个自动生成的值)
By default, bulkCreate
no validation will be done on every object to be created, while this create
can be done.
In order for to bulkCreate
also run these validations, validata: true
the parameter must be passed, but this reduces performance.
const Foo = sequelize.define('foo', {
bar: {
type: DataTypes.TEXT,
validate: {
len: [4, 6]
}
}
});
// 这不会引发错误,两个实例都将被创建
await Foo.bulkCreate([
{
name: 'abc123' },
{
name: 'name too long' }
]);
// 这将引发错误,不会创建任何内容,因为加上了 validdata: true,即会每一条都进行验证
await Foo.bulkCreate([
{
name: 'abc123' },
{
name: 'name too long' }
], {
validate: true });
2 deletedestory
await User.destory({
where:{
id: 1002 } });
truncate: true
destroy all content
await User.destory({
truncate: true });
3 changeupdate
await User.update({
age: 19}, {
where:{
id: 1002 } });
4 check finder
4.1 findAll
query all
// 查询所有用户
const users = await User.findAll()
const users = await User.findAll({
where: {
id: 2 } })
// attributes 返回指定属性
const users = await User.findAll({
attributes: ['name', 'age']
})
// attributes + exclude 排除某些属性
const users = await User.findAll({
attributes: {
exclude: ['age'] }
})
// 使用嵌套数组进行重命名属性
const users = await User.findAll({
attributes: ['name', ['age','age2']]
})
select * from User
select * from User where id = 2
select name, age from User/* 返回指定字段 */
select name, age as age2 from User/* as 重命名属性 */
4.2 findByPk
findByPk
method to get exactly one entry from the table using the provided primary key.
const res = await User.findByPk(123);
if (res === null) {
console.log('Not found!');
} else {
console.log(res instanceof User); // true 它的主键是 123
}
4.3 findOne
findOne
method gets the first entry it finds (which may satisfy the optional query parameters provided).
const res = await User.findOne({
where: {
id: '123' } });
if (res === null) {
console.log('Not found!');
} else {
console.log(res instanceof User); // true
console.log(res.id); // '123'
}
4.4 findOrCreate
Create if not found. The return value is an instance (found or created) and a boolean, true for created.
const [user, created] = await User.findOrCreate({
where: {
username: '小徐' },
defaults: {
job: 'Technical Lead JavaScript'
}
});
console.log(user.username); // '小徐'
console.log(user.job); // 这可能是也可能不是 'Technical Lead JavaScript'
console.log(created); // 指示此实例是否刚刚创建的布尔值
if (created) {
// created === true 即是创建
console.log(user.job); // 这里肯定是 'Technical Lead JavaScript'
}
4.5 findAndCountAll
Often used to handle queries related to pagination, this method is findAll
a count
convenience method that combines and .
(1) When not group
provided , findAndCountAll
the method returns an object with two properties:
count
: an integer (total number of records matching the query)rows
: an array object (obtained records)
(2) group
When , findAndCountAll
the method returns an object with two properties:
count
- an array object (contains total and preset properties in each group)rows
- an array object (obtained records)
const {
count, rows } = await User.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
});
console.log(count);
console.log(rows);