-
sequelize.define(modelName, attributes, options)
: 定义一个模型,用于表示数据库中的表。举例://创建模型 module.exports = (app) => { const { STRING, INTEGER, BIGINT, DATE } = app.Sequelize; const Patient = app.model.define("patient", { id: { type: BIGINT(20), primaryKey: true, autoIncrement: true, allowNull: false, }, username: { type: STRING(20), allowNull: false, unique: true, // 添加唯一索引 }, password: { type: STRING(20), allowNull: false, }, }); return Patient; };
-
Model.sync(options)
: 根据模型定义创建对应的数据库表。如果表已存在,可以使用force: true
选项来删除原有表并重新创建。app.beforeStart(async () => { // 同步数据库表结构 await app.model.sync({ force: true }); });
-
Model.create(values, options)
: 在数据库中插入一条记录。async addPatient() { const { ctx, app } = this; const patient = await app.model.Patient.create(ctx.request.body); ctx.body = { code: "200", msg: "success", data: patient, }; }
-
Model.findAll(options)
: 查询满足条件的所有记录。async getList() { const { ctx, app } = this; const patients = await app.model.Patient.findAll(); const total = patients.length; ctx.body = { total: total, code: "200", msg: "success", data: patients, }; }
-
Model.findByPk(id, options)
: 根据主键查找一条记录。async resetPassword() { const { ctx } = this; const { id } = ctx.request.body; try { const patient = await ctx.model.Patient.findByPk(id); if (patient) { patient.password = "123456"; await patient.save(); ctx.body = { code: "200", msg: "success", }; } else { ctx.body = { code: "404", msg: "not found", }; } } catch (error) { ctx.body = { code: "500", msg: "server error", }; } }
-
Model.findOne(options)
: 查询满足条件的第一条记录。/* 登录接口 */ async login() { const { ctx, app } = this; const { username, password } = ctx.request.body; try { // 检查用户是否已注册 const isRegistered = await app.model.Patient.findOne({ where: { username, }, }); if (!isRegistered) { ctx.body = { code: "404", msg: "该用户尚未注册", }; return; } // 检查用户名和密码是否匹配 const patient = await app.model.Patient.findOne({ where: { username, password, }, }); if (patient) { ctx.body = { code: "200", msg: "登录成功", data: patient, }; } else { ctx.body = { code: "401", msg: "用户名或密码错误", }; } } catch (error) { ctx.body = { code: "500", msg: "服务器错误", }; } }
-
Model.update(values, options)
: 更新满足条件的记录。async updatePatient() { const { ctx, app } = this; const { id, ...updatedFields } = ctx.request.body; try { const patient = await app.model.Patient.findByPk(id); if (!patient) { ctx.status = 404; return; } await patient.update(updatedFields); ctx.body = { code: "200", msg: "success", data: patient, }; } catch (error) { // 处理更新过程中的错误 console.error(error); ctx.status = 500; ctx.body = { code: "500", msg: "更新失败", }; } }
-
Model.destroy(options)
: 删除满足条件的记录。async delPatient() { const { ctx } = this; const { id } = ctx.request.body; try { const result = await ctx.model.Patient.destroy({ where: { id }, }); if (result) { ctx.body = { code: "200", msg: "success", }; } else { ctx.body = { code: "404", msg: "not found", }; } } catch (error) { ctx.body = { code: "500", msg: "server error", }; } }
-
Model.belongsTo(TargetModel, options)
: 建立模型之间的一对一关系。假设我们有两个模型:User
和Profile
,它们之间是一对一的关系,一个用户只拥有一个个人资料。首先,我们需要定义User
模型和Profile
模型:// User.js module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define('User', { id: { type: INTEGER, primaryKey: true }, username: STRING, // ... }); return User; }; // Profile.js module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const Profile = app.model.define('Profile', { id: { type: INTEGER, primaryKey: true }, userId: INTEGER, bio: STRING, // ... }); return Profile; };
然后,我们可以在
User
模型中使用belongsTo
方法来建立与Profile
模型的关联:// User.js module.exports = app => { // ... User.associate = function() { app.model.User.belongsTo(app.model.Profile, { foreignKey: 'userId' }); }; return User; };
我们通过调用
app.model.User.belongsTo(app.model.Profile, { foreignKey: 'userId' })
来建立User
模型与Profile
模型之间的关联关系。通过foreignKey
选项,我们指定了关联字段为userId
,即Profile
模型中的外键。有了这个关联关系,我们就可以使用 Sequelize 提供的查询方法来进行相关操作。例如,查询某个用户及其对应的个人资料:
const user = await app.model.User.findByPk(userId, { include: app.model.Profile, }); console.log(user.Profile);
通过使用
include
选项,可以将Profile
模型与查询结果关联起来,并通过user.Profile
来访问关联的个人资料对象。 -
Model.hasMany(TargetModel, options)
: 建立模型之间的一对多关系。假设我们有两个模型:User
和Post
,它们之间是一对多的关系,一个用户可以拥有多篇文章。首先,我们需要定义User
模型和Post
模型:
然后,我们可以在 User 模型中使用 hasMany 方法来建立与 Post 模型的关联:// User.js module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define('User', { id: { type: INTEGER, primaryKey: true }, username: STRING, // ... }); return User; }; // Post.js module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const Post = app.model.define('Post', { id: { type: INTEGER, primaryKey: true }, title: STRING, content: STRING, userId: INTEGER, // ... }); return Post; };
// User.js module.exports = app => { // ... User.associate = function() { app.model.User.hasMany(app.model.Post, { foreignKey: 'userId' }); }; return User; };
通过调用
app.model.User.hasMany(app.model.Post, { foreignKey: 'userId' })
来建立User
模型与Post
模型之间的关联关系。通过foreignKey
选项,我们指定了关联字段为userId
,即Post
模型中的外键。有了这个关联关系,我们就可以使用 Sequelize 提供的查询方法来进行相关操作。例如,查询某个用户及其对应的所有文章:
const user = await app.model.User.findByPk(userId, { include: app.model.Post, }); console.log(user.Posts);
通过使用
include
选项,我们可以将Post
模型与查询结果关联起来,并通过user.Posts
来访问关联的所有文章对象。 -
Model.belongsToMany(TargetModel, options)
: 建立模型之间的多对多关系。
-
假设我们有两个模型:
User
和Role
,它们之间是多对多的关系,一个用户可以拥有多个角色,一个角色也可以被多个用户拥有。 -
首先,我们需要定义
User
模型和Role
模型,并创建它们之间的关联表: -
// User.js module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define('User', { id: { type: INTEGER, primaryKey: true }, username: STRING, // ... }); return User; }; // Role.js module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const Role = app.model.define('Role', { id: { type: INTEGER, primaryKey: true }, name: STRING, // ... }); return Role; }; // UserRole.js module.exports = app => { const { INTEGER } = app.Sequelize; const UserRole = app.model.define('UserRole', { userId: INTEGER, roleId: INTEGER, }); return UserRole; };
然后,我们可以在
User
模型中使用belongsToMany
方法来建立与Role
模型的关联: -
// User.js module.exports = app => { // ... User.associate = function() { app.model.User.belongsToMany(app.model.Role, { through: app.model.UserRole, foreignKey: 'userId', }); }; return User; };
通过调用
app.model.User.belongsToMany(app.model.Role, { through: app.model.UserRole, foreignKey: 'userId' })
来建立User
模型与Role
模型之间的关联关系。通过through
选项,我们指定了关联表为UserRole
,通过foreignKey
选项,我们指定了关联字段为userId
,即UserRole
表中的外键。有了这个关联关系,我们就可以使用 Sequelize 提供的查询方法来进行相关操作。例如,查询某个用户及其对应的所有角色: -
const user = await app.model.User.findByPk(userId, { include: app.model.Role, }); console.log(user.Roles);
过使用
include
选项,我们可以将Role
模型与查询结果关联起来,并通过user.Roles
来访问关联的所有角色对象。
12.findAndCountAll(options)
查询满足条件的所有记录,并返回总记录数和查询结果。
async searchPatient() {
const { ctx, app } = this;
const { username, Gender, page, limit } = ctx.query;
const where = {};
if (username) {
where.username = { [app.Sequelize.Op.like]: `%${username}%` };
}
if (Gender) {
where.Gender = { [app.Sequelize.Op.like]: `%${Gender}%` };
}
const pageNumber = parseInt(page);
const limitNumber = parseInt(limit);
console.log(`pageNumber: ${pageNumber}, limitNumber: ${limitNumber}`);
const patients = await app.model.Patient.findAndCountAll({
where,
offset: (pageNumber - 1) * limitNumber,
limit: limitNumber,
});
ctx.body = {
code: "200",
msg: "success",
data: patients.rows,
total: patients.count,
};
}