{"id":13487531,"url":"https://github.com/eggjs/egg-sequelize","last_synced_at":"2025-03-27T22:31:21.523Z","repository":{"id":50017524,"uuid":"79544712","full_name":"eggjs/egg-sequelize","owner":"eggjs","description":"Sequelize for Egg.js","archived":false,"fork":false,"pushed_at":"2024-02-29T04:43:26.000Z","size":158,"stargazers_count":614,"open_issues_count":10,"forks_count":136,"subscribers_count":21,"default_branch":"master","last_synced_at":"2024-10-29T21:05:54.396Z","etag":null,"topics":["egg","egg-plugin","orm","sequelize"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eggjs.png","metadata":{"files":{"readme":"README.md","changelog":"History.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2017-01-20T09:19:26.000Z","updated_at":"2024-10-12T12:40:28.000Z","dependencies_parsed_at":"2024-04-16T07:04:46.833Z","dependency_job_id":"d9d1cdf2-2a4c-4c46-8ee4-118b4f3b0dd1","html_url":"https://github.com/eggjs/egg-sequelize","commit_stats":{"total_commits":110,"total_committers":32,"mean_commits":3.4375,"dds":0.5909090909090908,"last_synced_commit":"a126c2bcb9250b8d12f8782edc6642b2604c9eff"},"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Fegg-sequelize","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Fegg-sequelize/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Fegg-sequelize/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eggjs%2Fegg-sequelize/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eggjs","download_url":"https://codeload.github.com/eggjs/egg-sequelize/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":222133501,"owners_count":16936782,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["egg","egg-plugin","orm","sequelize"],"created_at":"2024-07-31T18:01:00.346Z","updated_at":"2024-10-30T22:31:06.510Z","avatar_url":"https://github.com/eggjs.png","language":"JavaScript","readme":"# egg-sequelize\n\n[Sequelize](http://sequelizejs.com) plugin for Egg.js.\n\n\u003e NOTE: This plugin just for integrate Sequelize into Egg.js, more documentation please visit http://sequelizejs.com.\n\n[![NPM version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![Test coverage][codecov-image]][codecov-url]\n[![David deps][david-image]][david-url]\n[![Known Vulnerabilities][snyk-image]][snyk-url]\n[![npm download][download-image]][download-url]\n\n[npm-image]: https://img.shields.io/npm/v/egg-sequelize.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/egg-sequelize\n[travis-image]: https://img.shields.io/travis/eggjs/egg-sequelize.svg?style=flat-square\n[travis-url]: https://travis-ci.org/eggjs/egg-sequelize\n[codecov-image]: https://codecov.io/gh/eggjs/egg-sequelize/branch/master/graph/badge.svg\n[codecov-url]: https://codecov.io/gh/eggjs/egg-sequelize\n[david-image]: https://img.shields.io/david/eggjs/egg-sequelize.svg?style=flat-square\n[david-url]: https://david-dm.org/eggjs/egg-sequelize\n[snyk-image]: https://snyk.io/test/npm/egg-sequelize/badge.svg?style=flat-square\n[snyk-url]: https://snyk.io/test/npm/egg-sequelize\n[download-image]: https://img.shields.io/npm/dm/egg-sequelize.svg?style=flat-square\n[download-url]: https://npmjs.org/package/egg-sequelize\n\n## Install\n\n```bash\n$ npm i --save egg-sequelize\n$ npm install --save mysql2 # For both mysql and mariadb dialects\n\n# Or use other database backend.\n$ npm install --save pg pg-hstore # PostgreSQL\n$ npm install --save tedious # MSSQL\n```\n\n## Usage \u0026 configuration\n\n\u003e Read the [tutorials](https://eggjs.org/en/tutorials/sequelize.html) to see a full example.\n\n- Enable plugin in `config/plugin.js`\n\n``` js\nexports.sequelize = {\n  enable: true,\n  package: 'egg-sequelize'\n}\n```\n\n- Edit your own configurations in `conif/config.{env}.js`\n\n```js\nexports.sequelize = {\n  dialect: 'mysql', // support: mysql, mariadb, postgres, mssql\n  database: 'test',\n  host: 'localhost',\n  port: 3306,\n  username: 'root',\n  password: '',\n  // delegate: 'myModel', // load all models to `app[delegate]` and `ctx[delegate]`, default to `model`\n  // baseDir: 'my_model', // load all files in `app/${baseDir}` as models, default to `model`\n  // exclude: 'index.js', // ignore `app/${baseDir}/index.js` when load models, support glob and array\n  // more sequelize options\n};\n```\n\nYou can also use the `connection uri` to configure the connection:\n\n```js\nexports.sequelize = {\n  dialect: 'mysql', // support: mysql, mariadb, postgres, mssql\n  connectionUri: 'mysql://root:@127.0.0.1:3306/test',\n  // delegate: 'myModel', // load all models to `app[delegate]` and `ctx[delegate]`, default to `model`\n  // baseDir: 'my_model', // load all files in `app/${baseDir}` as models, default to `model`\n  // exclude: 'index.js', // ignore `app/${baseDir}/index.js` when load models, support glob and array\n  // more sequelize options\n};\n```\n\negg-sequelize has a default sequelize options below\n\n```js\n{\n    delegate: 'model',\n    baseDir: 'model',\n    logging(...args) {\n      // if benchmark enabled, log used\n      const used = typeof args[1] === 'number' ? `[${args[1]}ms]` : '';\n      app.logger.info('[egg-sequelize]%s %s', used, args[0]);\n    },\n    host: 'localhost',\n    port: 3306,\n    username: 'root',\n    benchmark: true,\n    define: {\n      freezeTableName: false,\n      underscored: true,\n    },\n  };\n```\n\nMore documents please refer to [Sequelize.js](http://docs.sequelizejs.com/manual/installation/usage.html)\n\n## Model files\n\nPlease put models under `app/model` dir by default.\n\n## Conventions\n\n| model file       | class name              |\n| ---------------- | ----------------------- |\n| `user.js`        | `app.model.User`        |\n| `person.js`      | `app.model.Person`      |\n| `user_group.js`  | `app.model.UserGroup`   |\n| `user/profile.js`| `app.model.User.Profile`|\n\n- Tables always has timestamp fields: `created_at datetime`, `updated_at datetime`.\n- Use underscore style column name, for example: `user_id`, `comments_count`.\n\n## Examples\n\n### Standard\n\nDefine a model first.\n\n\u003e NOTE: `options.delegate` default to `model`, so `app.model` is an [Instance of Sequelize](http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor), so you can use methods like: `app.model.sync, app.model.query ...`\n\n```js\n// app/model/user.js\n\nmodule.exports = app =\u003e {\n  const { STRING, INTEGER, DATE } = app.Sequelize;\n\n  const User = app.model.define('user', {\n    login: STRING,\n    name: STRING(30),\n    password: STRING(32),\n    age: INTEGER,\n    last_sign_in_at: DATE,\n    created_at: DATE,\n    updated_at: DATE,\n  });\n\n  User.findByLogin = async function(login) {\n    return await this.findOne({\n      where: {\n        login: login\n      }\n    });\n  }\n\n  // don't use arraw function\n  User.prototype.logSignin = async function() {\n    return await this.update({ last_sign_in_at: new Date() });\n  }\n\n  return User;\n};\n\n```\n\nNow you can use it in your controller:\n\n```js\n// app/controller/user.js\nclass UserController extends Controller {\n  async index() {\n    const users = await this.ctx.model.User.findAll();\n    this.ctx.body = users;\n  }\n\n  async show() {\n    const user = await this.ctx.model.User.findByLogin(this.ctx.params.login);\n    await user.logSignin();\n    this.ctx.body = user;\n  }\n}\n```\n\n### Associate\n\nDefine all your associations in `Model.associate()` and egg-sequelize will execute it after all models loaded. See example below.\n\n### Multiple Datasources\n\negg-sequelize support load multiple datasources independently. You can use `config.sequelize.datasources` to configure and load multiple datasources.\n\n```js\n// config/config.default.js\nexports.sequelize = {\n  datasources: [\n    {\n      delegate: 'model', // load all models to app.model and ctx.model\n      baseDir: 'model', // load models from `app/model/*.js`\n      database: 'biz',\n      // other sequelize configurations\n    },\n    {\n      delegate: 'admninModel', // load all models to app.adminModel and ctx.adminModel\n      baseDir: 'admin_model', // load models from `app/admin_model/*.js`\n      database: 'admin',\n      // other sequelize configurations\n    },\n  ],\n};\n```\n\nThen we can define model like this:\n\n```js\n// app/model/user.js\nmodule.exports = app =\u003e {\n  const { STRING, INTEGER, DATE } = app.Sequelize;\n\n  const User = app.model.define('user', {\n    login: STRING,\n    name: STRING(30),\n    password: STRING(32),\n    age: INTEGER,\n    last_sign_in_at: DATE,\n    created_at: DATE,\n    updated_at: DATE,\n  });\n\n  return User;\n};\n\n// app/admin_model/user.js\nmodule.exports = app =\u003e {\n  const { STRING, INTEGER, DATE } = app.Sequelize;\n\n  const User = app.adminModel.define('user', {\n    login: STRING,\n    name: STRING(30),\n    password: STRING(32),\n    age: INTEGER,\n    last_sign_in_at: DATE,\n    created_at: DATE,\n    updated_at: DATE,\n  });\n\n  return User;\n};\n```\n\nIf you define the same model for different datasource, the same model file will be excute twice for different database, so we can use the secound argument to get the sequelize instance:\n\n```js\n// app/model/user.js\n// if this file will load multiple times for different datasource\n// we can use the secound argument to get the sequelize instance\nmodule.exports = (app, model) =\u003e {\n  const { STRING, INTEGER, DATE } = app.Sequelize;\n\n  const User = model.define('user', {\n    login: STRING,\n    name: STRING(30),\n    password: STRING(32),\n    age: INTEGER,\n    last_sign_in_at: DATE,\n    created_at: DATE,\n    updated_at: DATE,\n  });\n\n  return User;\n};\n```\n\n### Customize Sequelize\n\nBy default, egg-sequelize will use sequelize@5, you can cusomize sequelize version by pass sequelize instance with `config.sequelize.Sequelize` like this:\n\n```js\n// config/config.default.js\nexports.sequelize = {\n  Sequelize: require('sequelize'),\n};\n```\n\n### Full example\n\n```js\n// app/model/post.js\n\nmodule.exports = app =\u003e {\n  const { STRING, INTEGER, DATE } = app.Sequelize;\n\n  const Post = app.model.define('Post', {\n    name: STRING(30),\n    user_id: INTEGER,\n    created_at: DATE,\n    updated_at: DATE,\n  });\n\n  Post.associate = function() {\n    app.model.Post.belongsTo(app.model.User, { as: 'user' });\n  }\n\n  return Post;\n};\n```\n\n\n```js\n// app/controller/post.js\nclass PostController extends Controller {\n  async index() {\n    const posts = await this.ctx.model.Post.findAll({\n      attributes: [ 'id', 'user_id' ],\n      include: { model: this.ctx.model.User, as: 'user' },\n      where: { status: 'publish' },\n      order: 'id desc',\n    });\n\n    this.ctx.body = posts;\n  }\n\n  async show() {\n    const post = await this.ctx.model.Post.findByPk(this.params.id);\n    const user = await post.getUser();\n    post.setDataValue('user', user);\n    this.ctx.body = post;\n  }\n\n  async destroy() {\n    const post = await this.ctx.model.Post.findByPk(this.params.id);\n    await post.destroy();\n    this.ctx.body = { success: true };\n  }\n}\n```\n\n## Sync model to db\n\n**We strongly recommend you to use [Sequelize - Migrations](http://docs.sequelizejs.com/manual/tutorial/migrations.html) to create or migrate database.**\n\n**This code should only be used in development.**\n\n```js\n// {app_root}/app.js\nmodule.exports = app =\u003e {\n  if (app.config.env === 'local' || app.config.env === 'unittest') {\n    app.beforeStart(async () =\u003e {\n      await app.model.sync({force: true});\n    });\n  }\n};\n```\n\n## Migration\n\nUsing [sequelize-cli](https://github.com/sequelize/cli) to help manage your database, data structures and seed data. Please read [Sequelize - Migrations](http://docs.sequelizejs.com/manual/tutorial/migrations.html) to learn more infomations.\n\n## Recommended example\n\n- https://github.com/eggjs/examples/tree/master/sequelize/\n\n## Questions \u0026 Suggestions\n\nPlease open an issue [here](https://github.com/eggjs/egg/issues).\n\n## License\n\n[MIT](LICENSE)\n\n","funding_links":[],"categories":["仓库","Plugins"],"sub_categories":["插件"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feggjs%2Fegg-sequelize","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feggjs%2Fegg-sequelize","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feggjs%2Fegg-sequelize/lists"}