返回

Egg.js 里使用 Sequelize 构建模型的疑难杂症

前端

前言

在软件开发中,模型是一个重要的概念,它代表了现实世界中的实体,比如用户、产品、订单等。在 Egg.js 中,Sequelize 是一个流行的 ORM(对象关系映射)框架,它可以帮助我们轻松地将模型映射到数据库表,并进行 CRUD(创建、读取、更新、删除)操作。

创建模型

在 Egg.js 中创建模型非常简单,只需要定义一个类,并继承自 Sequelize.Model 类即可。例如,我们可以创建一个 User 模型,如下所示:

import { Model, DataTypes } from 'sequelize';

class User extends Model {
  id: number;
  name: string;
  age: number;
}

User.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: {
    type: DataTypes.STRING(255),
    allowNull: false,
  },
  age: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
}, {
  sequelize,
  modelName: 'User',
});

模型关系

在现实世界中,实体之间往往存在着各种各样的关系,比如一对一、一对多、多对多等。在 Sequelize 中,我们可以通过定义模型之间的关联来表示这些关系。例如,我们可以定义一个 Order 模型,并将其与 User 模型建立一对多的关联,如下所示:

import { Model, DataTypes } from 'sequelize';

class Order extends Model {
  id: number;
  userId: number;
  amount: number;
}

Order.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
  },
}, {
  sequelize,
  modelName: 'Order',
});

Order.belongsTo(User, { foreignKey: 'userId' });

数据查询

在 Sequelize 中,我们可以通过各种方法对数据库进行查询。例如,我们可以使用 findAll() 方法查询所有用户,如下所示:

const users = await User.findAll();

我们也可以使用 findOne() 方法查询单个用户,如下所示:

const user = await User.findOne({ where: { id: 1 } });

数据更新

在 Sequelize 中,我们可以通过各种方法更新数据库中的数据。例如,我们可以使用 update() 方法更新单个用户,如下所示:

await User.update({ age: 20 }, { where: { id: 1 } });

我们也可以使用 destroy() 方法删除单个用户,如下所示:

await User.destroy({ where: { id: 1 } });

总结

以上就是如何在 Egg.js 中使用 Sequelize 创建模型、定义模型关系、进行数据查询和数据更新的基本方法。更多详细的内容,请参考 Sequelize 的官方文档。