{"id":13781589,"url":"https://github.com/thinkjs/think-sequelize","last_synced_at":"2026-03-14T15:51:15.853Z","repository":{"id":57110243,"uuid":"101162665","full_name":"thinkjs/think-sequelize","owner":"thinkjs","description":"Sequelize Extend for ThinkJS 3.x","archived":false,"fork":false,"pushed_at":"2021-07-02T00:19:51.000Z","size":35,"stargazers_count":13,"open_issues_count":0,"forks_count":4,"subscribers_count":12,"default_branch":"master","last_synced_at":"2025-03-30T01:04:56.217Z","etag":null,"topics":["sequelize","think-model","thinkjs","thinkjs3"],"latest_commit_sha":null,"homepage":null,"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/thinkjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-08-23T09:26:54.000Z","updated_at":"2021-11-04T05:30:05.000Z","dependencies_parsed_at":"2022-08-20T20:50:46.313Z","dependency_job_id":null,"html_url":"https://github.com/thinkjs/think-sequelize","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thinkjs%2Fthink-sequelize","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thinkjs%2Fthink-sequelize/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thinkjs%2Fthink-sequelize/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thinkjs%2Fthink-sequelize/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thinkjs","download_url":"https://codeload.github.com/thinkjs/think-sequelize/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247522316,"owners_count":20952520,"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":["sequelize","think-model","thinkjs","thinkjs3"],"created_at":"2024-08-03T18:01:27.404Z","updated_at":"2026-03-14T15:51:15.808Z","avatar_url":"https://github.com/thinkjs.png","language":"JavaScript","readme":"# think-sequelize\n\n[![npm](https://img.shields.io/npm/v/think-sequelize.svg?style=flat-square)]()\n[![Travis](https://img.shields.io/travis/thinkjs/think-sequelize.svg?style=flat-square)]()\n\u003c!-- [![Coveralls](https://img.shields.io/coveralls/thinkjs/think-sequelize/master.svg?style=flat-square)]() --\u003e\n\nWrap sequelize for ThinkJS 3.x\n\nSequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and more.\n\n## Install\n\n```sh\nnpm install think-sequelize --save\n\n# add one of the following:\n$ npm install --save pg@6 pg-hstore # Note that `pg@7` is not supported yet\n$ npm install --save mysql2\n$ npm install --save sqlite3\n$ npm install --save tedious # MSSQL\n\n```\n\n## How to Use\n\n### Config Extend\n\nChange file `src/config/extend.js` (in multi module project, file is `src/common/config/extend.js`), add config:\n\n```js\nconst sequelize = require('think-sequelize');\n\nmodule.exports = [\n  sequelize(think.app)\n]\n```\n\nWhen add sequelize extend, it will add methods below:\n\n* `think.Sequel` {Class} Base class(it's extends from sequelize model), model class should extends this class.\n\n  * `think.Sequel.Sequel` sequelize object (equal require('sequelize'))\n  * `think.Sequel.Relation` sequelize relation type\n\n* `think.sequel` {Function} get sequel instance\n* `ctx.sequel` {Function} get sequel instance\n* `controller.sequel` {Function} get sequel instance\n* `service.sequel` {Function} get sequel instance\n\n### Config Adapter\n\nChange file `src/config/adapter.js` (in multi module project, file is `src/common/config/adapter.js`), add config:\n\n```js\nexports.model = {\n  type: 'sequel',\n  sequel: {\n    prefix: 'think_',\n    logConnect: false,\n    database: 'think-demo',\n    user: 'root',\n    password: 'root',\n    options: {\n      host: '127.0.0.1',\n      dialect: 'mysql',\n      logging: false,\n      define: {\n        timestamps: false\n      }\n    }\n  },\n}\n```\n\nor config connectionString:\n\n```js\nexports.model = {\n  type: 'sequel',\n  sequel: {\n    connectionString: 'mysql://root:root@127.0.0.1/think-demo',\n    prefix: 'think_',\n    logConnect: false,\n    options: {\n      logging: false\n    }\n  }\n}\n```\n\nFor more options see at [http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html](http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html).\n\n### Create Model Class\n\nCreate model class extends from `think.Sequel`:\n\n```js\n// src/model/player.js\nmodule.exports = class extends think.Sequel {\n  get schema() {\n    return {\n      attributes: {\n        id: {\n          type: think.Sequel.Sequel.BIGINT,\n          primaryKey: true\n        },\n        teamId: think.Sequel.Sequel.BIGINT,\n        name: think.Sequel.Sequel.STRING(255),\n      },\n      options: { // will merge with options.define config of sequel in src/config/adapter.js\n        timestamps: false,\n        freezeTableName: true,\n        tableName: 'think_player',\n      }\n    }\n  }\n}\n```\n\nSchema's attributes and options will be passed to sequelize's define method. For more model definition see at [http://docs.sequelizejs.com/manual/tutorial/models-definition.html](http://docs.sequelizejs.com/manual/tutorial/models-definition.html);\n\n```js\nsequelize.define('name', {attributes}, {options})\n```\n\nThe schema's `options` will merge with `options.define` in `src/config/adapter.js`.\n\nIf you want every model's `timestamps: false`, you can write in sequel's `options.define` config of `src/config/adapter.js`.\n\nAnd you can rewrite common schema config in every model's schema.\n\n\n### Add instance methods\n\n```js\nmodule.exports = class extends think.Sequel {\n  constructor(...props) {\n    super(...props);\n  }\n\n  get schema() {\n    return {\n      attributes: {\n        id: {\n          type: think.Sequel.Sequel.BIGINT,\n          primaryKey: true\n        },\n        teamId: think.Sequel.Sequel.BIGINT, // belongsTo, 为当前模型添加外键\n        name: think.Sequel.Sequel.STRING(255),\n      },\n      options: {\n        timestamps: false,\n        freezeTableName: true,\n        tableName: 'think_player',\n      }\n    }\n  }\n\n  get instanceMethods() {\n    return {\n      test() {\n        console.log(this.id);\n      }\n    }\n  }\n}\n```\n\n`instanceMethods` return an `object`,each object's item is a function. Arrow function is disabled.\n\nIf you just want add instance methods one by one in model, you can do like this:\n\n```js\nmodule.exports = class extends think.Sequel {\n  constructor(...props) {\n    super(...props);\n    this.addInstanceMethod(function test() { // anonymous fn is disabled, arrow fn is disabled\n      console.log(this.id);\n    });\n  }\n}\n```\nThese methods are added to `sequelize.define(*).prototype`!\n\n### Get Model Instance\n\nYou can get sequel class instance by `think.sequel`, `ctx.sequel`, `service.sequel` or `controller.sequel`.\n\n```js\nmodule.exports = class extends think.Controller {\n  async indexAction() {\n    const player = this.sequel('player');\n    const data = await player.findAll();\n  }\n}\n```\n\nIf default model adapter type is not `sequel`, the second argument must be set, such as:\n\n```js\n// in src/config/adapter.js (in multi module project, file is `src/common/config/adapter.js`)\nexports.model = {\n  type: 'mysql',\n  common: {\n    // ...\n  },\n  sequel: {\n    // ...\n  },\n  mysql: {\n    // ...\n  }\n}\n```\n\nWith the config above, you should use sequelize like this:\n\n```js\nmodule.exports = class extends think.Controller {\n  async indexAction() {\n    const player = this.sequel('player', 'sequel'); // use `sequel` adapter type\n    const data = await player.findAll();\n  }\n}\n```\n\n### Relation\n\nSequelize support `hasOne`,`belongsTo`,`hasMany`,`belongsToMany` model relation type.\n`think.Sequel.Relation` wrap the relation types, it has the following values：\n\n```js\nthink.Sequel.Relation = {\n  HAS_ONE: 'hasOne',\n  BELONG_TO: 'belongsTo',\n  HAS_MANY: 'hasMany',\n  MANY_TO_MANY: 'belongsToMany'\n};\n```\n\nFor a better understanding, we give an example：\n\n  * one `player` has one `partner`\n  * one `player` belongs to one `team`\n  * one `player` has owned many `trophy`\n  * one `player` has many `teacher`, and one `teacher` has many `player`\n\n```js\n// src/model/player.js\nmodule.exports = class extends think.Sequel {\n  constructor(...props) {\n    super(...props);\n  }\n\n  get schema() {\n    return {\n      attributes: {\n        id: {\n          type: think.Sequel.Sequel.BIGINT,\n          primaryKey: true\n        },\n        teamId: think.Sequel.Sequel.BIGINT,\n        name: think.Sequel.Sequel.STRING(255),\n      },\n      options: {\n        timestamps: false,\n        freezeTableName: true,\n        tableName: 'think_player',\n      },\n      relations: [\n        { 'team': think.Sequel.Relation.BELONG_TO },\n        { 'partner': think.Sequel.Relation.HAS_ONE },\n        { 'trophy': think.Sequel.Relation.HAS_MANY },\n        {\n          'sequel/teacher': think.Sequel.Relation.MANY_TO_MANY,\n          options: {\n            through: think.sequel('teacher_player', 'sequel') // do not use this.sequel in schema\n          }\n        },\n      ]\n    }\n  }\n}\n```\n\nNOTE: If you want use sequelize model in `schema`, you should use `think.sequel` method instead of `this.sequel`, because `this.sequel` has't been initialized at this time.\n\nDefault `tableName` equal `${db prefix}_${model name}`, If you want custom `tableName`:\n\n```js\nget schema () {\n  return {\n    // ...\n    options: {\n      freezeTableName: true,     // set true\n      tableName: 'think_player', // custom tableName here\n    }\n  }\n}\n\n```\n\nOne player has one partner:\n\n```js\n// src/model/partner.js\nmodule.exports = class extends think.Sequel {\n  constructor(...props) {\n    super(...props);\n  }\n\n  get schema() {\n    return {\n      attributes: {\n        id: {\n          type: think.Sequel.Sequel.BIGINT,\n          primaryKey: true\n        },\n        playerId: think.Sequel.Sequel.BIGINT,\n        name: think.Sequel.Sequel.STRING(255),\n      }\n    }\n  }\n}\n```\n\nThen you can use like this:\n\n```js\nmodule.exports = class extends think.Controller {\n  constructor(...props) {\n    super(...props);\n  }\n  indexAction() {\n    let player = this.sequel('player', 'sequel');\n    let partner = this.sequel('partner', 'sequel');\n    return this.json(await player.findAll({\n      include: [\n        {\n          model: partner,\n        }\n      ]\n    }));\n  }\n}\n```\n\nOr you can use it in another way:\n\n```js\n// src/controller/index.js\nmodule.exports = class extends think.Controller {\n  constructor(...props) {\n    super(...props);\n  }\n  async indexAction() {\n    let player = this.sequel('player', 'sequel');\n    return this.json(await player.getAllPlayer());\n  }\n}\n\n// src/model/player.js\nmodule.exports = class extends think.Sequel {\n  // get schema and other ...\n  getAllPlayer() {\n    let partner = this.sequel('partner', 'sequel');\n    return this.findAll({\n      include: [\n        { model: partner }\n      ]\n    });\n  }\n}\n```\n\nOne player belongs to one team:\n\n```js\n// src/model/team.js\nmodule.exports = class extends think.Sequel {\n  constructor(...props) {\n    super(...props);\n  }\n\n  get schema() {\n    return {\n      attributes: {\n        id: {\n          type: think.Sequel.Sequel.BIGINT,\n          primaryKey: true\n        },\n        name: think.Sequel.Sequel.STRING(255),\n      }\n    }\n  }\n}\n```\n\nOne player owned many trophies:\n\n```js\n// src/model/trophy.js\nmodule.exports = class extends think.Sequel {\n  constructor(...props) {\n    super(...props);\n  }\n\n  get schema() {\n    return {\n      attributes: {\n        id: {\n          type: think.Sequel.Sequel.BIGINT,\n          primaryKey: true\n        },\n        playerId: think.Sequel.Sequel.BIGINT,\n        name: think.Sequel.Sequel.STRING(255),\n      }\n    }\n  }\n}\n```\n\nOne player has many teachers, and one teacher has many players:\n\n```js\n// src/model/teacher.js\nmodule.exports = class extends think.Sequel {\n  constructor(...props) {\n    super(...props);\n  }\n\n  get schema() {\n    return {\n      attributes: {\n        id: {\n          type: think.Sequel.Sequel.BIGINT,\n          primaryKey: true\n        },\n        name: think.Sequel.Sequel.STRING(255),\n      }\n    }\n  }\n}\n```\n\n```js\n// src/model/teacher_player.js\nmodule.exports = class extends think.Sequel {\n  constructor(...props) {\n    super(...props);\n  }\n\n  get schema() {\n    return {\n      attributes: {\n        id: {\n          type: think.Sequel.Sequel.BIGINT,\n          primaryKey: true\n        },\n        playerId: think.Sequel.Sequel.BIGINT,\n        teacherId: think.Sequel.Sequel.BIGINT,\n      }\n    }\n  }\n}\n```\n\n### CURD\n\nYou can use sequelize's model methods to execute ORM. Read documents [http://docs.sequelizejs.com/](http://docs.sequelizejs.com/) to get more information.\n\n","funding_links":[],"categories":["Extends"],"sub_categories":["websocket"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthinkjs%2Fthink-sequelize","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthinkjs%2Fthink-sequelize","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthinkjs%2Fthink-sequelize/lists"}