* Initialize a model, representing a table in the DB, with attributes and options. * * The table columns are defined by the hash that is given as the first argument. * Each attribute of the hash represents a column. * * @example * Project.init({ * columnA: { * type: Seq
(attributes, options = {})
| 956 | * @returns {Model} |
| 957 | */ |
| 958 | static init(attributes, options = {}) { |
| 959 | if (!options.sequelize) { |
| 960 | throw new Error('No Sequelize instance passed'); |
| 961 | } |
| 962 | |
| 963 | this.sequelize = options.sequelize; |
| 964 | |
| 965 | const globalOptions = this.sequelize.options; |
| 966 | |
| 967 | options = Utils.merge(_.cloneDeep(globalOptions.define), options); |
| 968 | |
| 969 | if (!options.modelName) { |
| 970 | options.modelName = this.name; |
| 971 | } |
| 972 | |
| 973 | options = Utils.merge({ |
| 974 | name: { |
| 975 | plural: Utils.pluralize(options.modelName), |
| 976 | singular: Utils.singularize(options.modelName) |
| 977 | }, |
| 978 | indexes: [], |
| 979 | omitNull: globalOptions.omitNull, |
| 980 | schema: globalOptions.schema |
| 981 | }, options); |
| 982 | |
| 983 | this.sequelize.runHooks('beforeDefine', attributes, options); |
| 984 | |
| 985 | if (options.modelName !== this.name) { |
| 986 | Object.defineProperty(this, 'name', { value: options.modelName }); |
| 987 | } |
| 988 | delete options.modelName; |
| 989 | |
| 990 | this.options = { |
| 991 | timestamps: true, |
| 992 | validate: {}, |
| 993 | freezeTableName: false, |
| 994 | underscored: false, |
| 995 | paranoid: false, |
| 996 | rejectOnEmpty: false, |
| 997 | whereCollection: null, |
| 998 | schema: null, |
| 999 | schemaDelimiter: '', |
| 1000 | defaultScope: {}, |
| 1001 | scopes: {}, |
| 1002 | indexes: [], |
| 1003 | whereMergeStrategy: 'overwrite', |
| 1004 | ...options |
| 1005 | }; |
| 1006 | |
| 1007 | // if you call "define" multiple times for the same modelName, do not clutter the factory |
| 1008 | if (this.sequelize.isDefined(this.name)) { |
| 1009 | this.sequelize.modelManager.removeModel(this.sequelize.modelManager.getModel(this.name)); |
| 1010 | } |
| 1011 | |
| 1012 | this.associations = {}; |
| 1013 | this._setupHooks(options.hooks); |
| 1014 | |
| 1015 | this.underscored = this.options.underscored; |
no test coverage detected