eggjs入门——sequelize常见方法及例子

  1. 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;
    };
    

  2. Model.sync(options): 根据模型定义创建对应的数据库表。如果表已存在,可以使用 force: true 选项来删除原有表并重新创建。

      app.beforeStart(async () => {
        // 同步数据库表结构
        await app.model.sync({ force: true });
      });

  3. 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,
        };
      }
    

  4. 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,
        };
      }

  5. 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",
          };
        }
      }

  6. 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: "服务器错误",
          };
        }
      }

  7. 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: "更新失败",
          };
        }
      }

  8. 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",
          };
        }
      }
  9. Model.belongsTo(TargetModel, options): 建立模型之间的一对一关系。假设我们有两个模型:UserProfile,它们之间是一对一的关系,一个用户只拥有一个个人资料。首先,我们需要定义 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 来访问关联的个人资料对象。

  10. Model.hasMany(TargetModel, options): 建立模型之间的一对多关系。假设我们有两个模型:UserPost,它们之间是一对多的关系,一个用户可以拥有多篇文章。首先,我们需要定义 User 模型和 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 模型中使用 hasMany 方法来建立与 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 来访问关联的所有文章对象。

  11. Model.belongsToMany(TargetModel, options): 建立模型之间的多对多关系。

  • 假设我们有两个模型:UserRole,它们之间是多对多的关系,一个用户可以拥有多个角色,一个角色也可以被多个用户拥有。

  • 首先,我们需要定义 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,
    };
  }

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值