{
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 } },
})