MCPcopy
hub / github.com/sequelize/sequelize / BelongsToMany

Class BelongsToMany

lib/associations/belongs-to-many.js:57–826  ·  view source on GitHub ↗

* Many-to-many association with a join table. * * When the join table has additional attributes, these can be passed in the options object: * * ```js * UserProject = sequelize.define('user_project', { * role: Sequelize.STRING * }); * User.belongsToMany(Project, { through: UserProject });

Source from the content-addressed store, hash-verified

55 * @see {@link Model.belongsToMany}
56 */
57class BelongsToMany extends Association {
58 constructor(source, target, options) {
59 super(source, target, options);
60
61 if (this.options.through === undefined || this.options.through === true || this.options.through === null) {
62 throw new AssociationError(`${source.name}.belongsToMany(${target.name}) requires through option, pass either a string or a model`);
63 }
64
65 if (!this.options.through.model) {
66 this.options.through = {
67 model: options.through
68 };
69 }
70
71 this.associationType = 'BelongsToMany';
72 this.targetAssociation = null;
73 this.sequelize = source.sequelize;
74 this.through = { ...this.options.through };
75 this.isMultiAssociation = true;
76 this.doubleLinked = false;
77
78 if (!this.as && this.isSelfAssociation) {
79 throw new AssociationError('\'as\' must be defined for many-to-many self-associations');
80 }
81
82 if (this.as) {
83 this.isAliased = true;
84
85 if (_.isPlainObject(this.as)) {
86 this.options.name = this.as;
87 this.as = this.as.plural;
88 } else {
89 this.options.name = {
90 plural: this.as,
91 singular: Utils.singularize(this.as)
92 };
93 }
94 } else {
95 this.as = this.target.options.name.plural;
96 this.options.name = this.target.options.name;
97 }
98
99 this.combinedTableName = Utils.combineTableNames(
100 this.source.tableName,
101 this.isSelfAssociation ? this.as || this.target.tableName : this.target.tableName
102 );
103
104 /*
105 * If self association, this is the target association - Unless we find a pairing association
106 */
107 if (this.isSelfAssociation) {
108 this.targetAssociation = this;
109 }
110
111 /*
112 * Find paired association (if exists)
113 */
114 _.each(this.target.associations, association => {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…