sequelize API 常用操作整理

sequelize 链接数据库配置

{
    dialect: 'mysql',
    database: 'databasename',
    host: '**********',
    port: ****,
    username: 'root',
    password: '***************',
    define: {
      timestamps: false //取消create_at 报错
    },
    dialectOptions: {
      dateStrings: true,
      typeCast: true
    },
    timezone: '+08:00' //修改时区
  }

查找数据

按主键查找

// 查找id为1的那一条数据
await model.table.findByPk(1)

按条件查找

await model.table.findOne({
        where: {
            username: '小明',
        },
        // 返回id和last_name字段,将last_name字段重命名为 role
        attributes: ['id', ['last_name','role']]
 });

查找全部数据

// 按照id降序返回,只返回前10条
await model.table.findAll({
    'order': "id desc",
    'limit': 10,
})

查找,如果没有则创建

await model.table.findOrCreate({
        where: {
            last_name: '小明'
        },
        defaults: { //创建的默认数据
            age: 5,
             last_name: '小明'
        },
    }).spread((res, created) => {
		//如果找到,则更新
            if (!created) res.update({age: 10})
   })

分页查找并排序

await model.table.findAndCountAll({
      offset,
      limit,
      order: [['id', 'desc']],
      attributes: ['username', 'is_superuser']
    });

关联查询多个表

首先在nodel中定义关联关系

Model.associate = function () {
    app.postgres.ChallengeSets.hasOne(app.postgres.ChallengeBinaryNodes,{
      foreignKey: 'cs_id',
      sourceKey: 'id',
      as: 'file',
    })

    app.postgres.ChallengeSets.hasMany(app.postgres.Crashes, {
      foreignKey: 'cs_id',
      sourceKey: 'id',
      as: 'crash',
    })

    app.postgres.ChallengeSets.hasMany(app.postgres.FuzzerStats, {
      foreignKey: 'cs_id',
      sourceKey: 'id',
      as: 'fuzzer',
    })
  }

关联查询

await ctx.postgres.models.challenge_sets.findAndCountAll({
      offset,
      limit,
      order:[['created_at', 'desc']],
      distinct: true,  //去除重复数据,必须
      include: [
        {
          model: ctx.postgres.models.challenge_binary_nodes,
          as: 'file',
          attributes: ['cb_type', 'name']
        },
        {
          model: ctx.postgres.models.crashes,
          as: 'crash', 
          attributes: ['explored', 'exploited']
        }, {
          model: ctx.postgres.models.fuzzer_stats,
          as: 'fuzzer', 
          attributes: ['cs_id']
        } 
      ],
      attributes: [
        'id', 'name', 'created_at'
      ]
    })

创建

批量创建

model.table.bulkCreate([
	{ip:1},
	{ip:2},
	{ip:3}
])
<------------------------------------->
const l = [];
for (let i = 0; i < 5; i++) {
    l.push({
        is_superuser: i,
        last_name: `bulkname-${i}`,
        first_name: i + 5,
    });
}

await model.table.bulkCreate(l, {
    // 这样创建语句中只有 role_id 和 role_name,会忽略 level
    fields: ['role_id', 'role_name']
});

单独创建

await model.table.create({
    id: 2,
    last_name: '小明',
});

更新

单独更新

const r = await model.table.findByPk(1)
r.update({
   last_name: '小红'
});

查找同时更新

await  model.table.update({
    last_name: '小红'
}, {
    where: {last_name: '小明'}
});

删除

单独删除

await model.table.destory({
	where: {
		// id:1  删除id为1的数据
	}
})

批量删除所有数据

// DEL, log, slow
async function table_clear(){
    const ctx = this.ctx
    await ctx.modelsql.models.tasks.destory({
		where:{}
	})
  }
// DDL,no log,faster
await ctx.modelsql.models.tasks.destroy({ 
        where: {},
       truncate: true 
}) 

批量删除筛选数据

const Sequelize = require('sequelize');
const Op = Sequelize.Op
await ctx.postgres.models.challenge_binary_nodes.destroy({
      where: { cs_id: { [Op.in]: idList } },
    })

猜你喜欢

转载自blog.csdn.net/zhai_865327/article/details/106897030
今日推荐