eggjs 使用: Sequelize

此模块是一个广泛使用的 ORM 框架,它支持 MySQL、PostgreSQL、SQLite 和 M...

5196 热度
1732 浏览

先安装

bash 复制代码
npm install --save egg-sequelize

config/plugin.js 中引入 egg-sequelize 插件

js 复制代码
sequelize: {
  enable: true,
  package: 'egg-sequelize',
};

config/config.default.js 中编写 sequelize 配置

js 复制代码
config.sequelize = {
  dialect: 'mysql',
  database: 'xxxx', //你的数据库名称
  username: 'xxxx', // 你的数据库帐号
  password: 'xxxx', //你的数据库密码
  host: 'localhost',
  port: '3306',
  define: {
    // 使用自定义的表名
    freezeTableName: true,
    // 自动生成时间戳 -小驼峰式
    timestamps: true,
    // 表名小驼峰
    underscored: false,
  },
};

app 目录下创建一个名为 model 的目录

再创建一个 js 文件比如:userConfig.js

创建一个表名为 users 内容如下

js 复制代码
'use strict';

module.exports = (app) => {
  const { STRING, INTEGER, DATE, BIGINT, TEXT } = app.Sequelize; // 获取数据类型
  // AI小程序分享、看视频、增加次数记录  
  const User = app.model.define(
    'users',
    {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      username: { type: STRING }, // 名字
      password: { type: STRING }, // 密码
      openid: { type: STRING },
      type: { type: STRING, allowNull: false, defaultValue: 1 }, // 1 普通用户   2 管理员
      add_time: { type: BIGINT, allowNull: false }, // 注册时间
    },
    {
      freezeTableName: true, // Model 对应的表名将与model名相同
      timestamps: false,
      paranoid: true, // 是否创建删除字段(逻辑删除)
      version: true,
    }
  );
  return User;
};
// 下面为各个方法的具体介绍
/*
  defaultValue 设置默认  Boolean
  allowNull 是否允许为空 Boolean
  unique 属性用来创建一个唯一约束. Boolean | string
  primaryKey 用于定义主键.  Boolean
  autoIncrement 可用于创建自增的整数列 Boolean
  comment 注释  string;
  references: {
    // 这是引用另一个模型
    model: Bar,

    // 这是引用模型的列名称
    key: 'id',

    // 这声明什么时候检查外键约束. 仅限PostgreSQL.
    deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
  }
*/

最后一步把下部分代码放在 router.js 里,可以启动项目的时候自动创建定义的表

js 复制代码
app.beforeStart(async () => {
  await app.model.sync({
    alter: true
  }); //force false 为不覆盖 true会删除再创建; alter true可以 添加或删除字段;
});
eggjs 使用: Sequelize

声明:Web前端小站 - 前端博客 - 王搏的个人博客|版权所有,违者必究|如未注明,均为原创

转载:转载请注明原文链接 - eggjs 使用: Sequelize

评论 (0)

0/50
暂无评论,快来抢沙发吧~