不要怂,就是干,撸起袖子干!

Commit c58bc413 by Mick Hansen

Merge pull request #2268 from sequelize/feat-association-scope

[WIP] Feature: Association scopes
2 parents 90965ba3 e07ef3cf
......@@ -2,9 +2,11 @@
- [BUG] Fixed an issue with foreign key object syntax for hasOne and belongsTo
- [FEATURE] Added `field` and `name` to the object form of foreign key definitions
- [FEATURE] Added support for calling `Promise.done`, thus explicitly ending the promise chain by calling done with no arguments. Done with a function argument still continues the promise chain, to maintain BC.
- [FEATURE] Added `scope` to hasMany association definitions, provides default values to association setters/finders [#2268](https://github.com/sequelize/sequelize/pull/2268)
#### Backwards compatability changes
- The `fieldName` property, used in associations with a foreign key object `(A.hasMany(B, { foreignKey: { ... }})`, has been renamed to `name` to avoid confusion with `field`.
- The naming of the join table entry for N:M association getters is now singular (like includes)
# v2.0.0-dev13
We are working our way to the first 2.0.0 release candidate.
......
......@@ -14,6 +14,7 @@ module.exports = (function() {
this.source = source;
this.target = target;
this.options = options;
this.scope = options.scope;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
......
......@@ -15,57 +15,48 @@ module.exports = (function() {
HasManyDoubleLinked.prototype.injectGetter = function(options, queryOptions) {
var self = this
, through = self.association.through
, targetAssociation = self.association.targetAssociation;
//fully qualify
var instancePrimaryKey = self.instance.Model.primaryKeyAttribute
, foreignPrimaryKey = self.association.target.primaryKeyAttribute;
, scopeWhere
, throughWhere;
if (this.association.scope) {
scopeWhere = {};
Object.keys(this.association.scope).forEach(function (attribute) {
scopeWhere[attribute] = this.association.scope[attribute];
}.bind(this));
}
options.where = new Utils.and([
new Utils.where(
through.rawAttributes[self.association.identifier],
self.instance[instancePrimaryKey]
),
new Utils.where(
through.rawAttributes[self.association.foreignIdentifier],
{
join: new Utils.literal([
self.QueryInterface.quoteTable(self.association.target.name),
self.QueryInterface.quoteIdentifier(foreignPrimaryKey)
].join('.'))
}
),
scopeWhere,
options.where
]);
if (Object(targetAssociation.through) === targetAssociation.through) {
queryOptions.hasJoinTableModel = true;
queryOptions.joinTableModel = through;
if (Object(through.model) === through.model) {
throughWhere = {};
throughWhere[self.association.identifier] = self.instance.get(self.association.source.primaryKeyAttribute);
if (!options.attributes) {
options.attributes = [
self.QueryInterface.quoteTable(self.association.target.name) + '.*'
];
}
if (options.joinTableAttributes) {
options.joinTableAttributes.forEach(function(elem) {
options.attributes.push(
self.QueryInterface.quoteTable(through.name) + '.' + self.QueryInterface.quoteIdentifier(elem) + ' as ' +
self.QueryInterface.quoteIdentifier(through.name + '.' + elem, true)
);
});
} else {
Utils._.forOwn(through.rawAttributes, function(elem, key) {
options.attributes.push(
self.QueryInterface.quoteTable(through.name) + '.' + self.QueryInterface.quoteIdentifier(key) + ' as ' +
self.QueryInterface.quoteIdentifier(through.name + '.' + key, true)
);
});
if (through && through.scope) {
Object.keys(through.scope).forEach(function (attribute) {
throughWhere[attribute] = through.scope[attribute];
}.bind(this));
}
options.include = options.include || [];
options.include.push({
model: through.model,
as: Utils.singularize(through.model.tableName),
attributes: options.joinTableAttributes,
association: {
isSingleAssociation: true,
source: self.association.target,
target: self.association.source,
identifier: self.association.foreignIdentifier
},
required: true,
where: throughWhere,
_pseudo: true
});
}
return self.association.target.findAllJoin([through.getTableName(), through.name], options, queryOptions);
return self.association.target.findAll(options, queryOptions);
};
HasManyDoubleLinked.prototype.injectSetter = function(oldAssociations, newAssociations, defaultAttributes) {
......@@ -97,10 +88,10 @@ module.exports = (function() {
if (!newObj) {
obsoleteAssociations.push(old);
} else if (Object(targetAssociation.through) === targetAssociation.through) {
var throughAttributes = newObj[self.association.through.name];
} else if (Object(targetAssociation.through.model) === targetAssociation.through.model) {
var throughAttributes = newObj[self.association.through.model.name];
// Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object)
if (throughAttributes instanceof self.association.through.DAO) {
if (throughAttributes instanceof self.association.through.model.Instance) {
throughAttributes = {};
}
......@@ -128,7 +119,7 @@ module.exports = (function() {
where[self.association.identifier] = ((sourceKeys.length === 1) ? self.instance[sourceKeys[0]] : self.instance.id);
where[foreignIdentifier] = foreignIds;
promises.push(self.association.through.destroy(where, options));
promises.push(self.association.through.model.destroy(where, options));
}
if (unassociatedObjects.length > 0) {
......@@ -138,19 +129,25 @@ module.exports = (function() {
attributes[self.association.identifier] = ((sourceKeys.length === 1) ? self.instance[sourceKeys[0]] : self.instance.id);
attributes[foreignIdentifier] = ((targetKeys.length === 1) ? unassociatedObject[targetKeys[0]] : unassociatedObject.id);
if (Object(targetAssociation.through) === targetAssociation.through) {
attributes = Utils._.defaults(attributes, unassociatedObject[targetAssociation.through.name], defaultAttributes);
if (Object(targetAssociation.through.model) === targetAssociation.through.model) {
attributes = Utils._.defaults(attributes, unassociatedObject[targetAssociation.through.model.name], defaultAttributes);
}
if (this.association.through.scope) {
Object.keys(this.association.through.scope).forEach(function (attribute) {
attributes[attribute] = this.association.through.scope[attribute];
}.bind(this));
}
return attributes;
});
}.bind(this));
promises.push(self.association.through.bulkCreate(bulk, options));
promises.push(self.association.through.model.bulkCreate(bulk, options));
}
if (changedAssociations.length > 0) {
changedAssociations.forEach(function(assoc) {
promises.push(self.association.through.update(assoc.attributes, assoc.where, options));
promises.push(self.association.through.model.update(assoc.attributes, assoc.where, options));
});
}
......@@ -175,17 +172,22 @@ module.exports = (function() {
if (exists) {
var where = attributes;
attributes = Utils._.defaults({}, newAssociation[targetAssociation.through.name], additionalAttributes);
attributes = Utils._.defaults({}, newAssociation[targetAssociation.through.model.name], additionalAttributes);
if (Object.keys(attributes).length) {
return targetAssociation.through.update(attributes, where, options);
return targetAssociation.through.model.update(attributes, where, options);
} else {
return Utils.Promise.resolve();
}
} else {
attributes = Utils._.defaults(attributes, newAssociation[targetAssociation.through.name], additionalAttributes);
attributes = Utils._.defaults(attributes, newAssociation[targetAssociation.through.model.name], additionalAttributes);
if (this.association.through.scope) {
Object.keys(this.association.through.scope).forEach(function (attribute) {
attributes[attribute] = this.association.through.scope[attribute];
}.bind(this));
}
return this.association.through.create(attributes, options);
return this.association.through.model.create(attributes, options);
}
};
......
......@@ -5,7 +5,6 @@ var Utils = require('./../utils')
module.exports = (function() {
var HasManySingleLinked = function(association, instance) {
this.__factory = association;
this.association = association;
this.instance = instance;
this.target = this.association.target;
......@@ -13,11 +12,19 @@ module.exports = (function() {
};
HasManySingleLinked.prototype.injectGetter = function(options, queryOptions) {
var scopeWhere = this.association.scope ? {} : null;
if (this.association.scope) {
Object.keys(this.association.scope).forEach(function (attribute) {
scopeWhere[attribute] = this.association.scope[attribute];
}.bind(this));
}
options.where = new Utils.and([
new Utils.where(
this.target.rawAttributes[this.association.identifier],
this.instance[this.source.primaryKeyAttribute])
,
this.instance[this.source.primaryKeyAttribute]
),
scopeWhere,
options.where
]);
......@@ -52,22 +59,22 @@ module.exports = (function() {
if (obsoleteAssociations.length > 0) {
// clear the old associations
var obsoleteIds = obsoleteAssociations.map(function(associatedObject) {
associatedObject[self.__factory.identifier] = (newAssociations.length < 1 ? null : self.instance.id);
associatedObject[self.association.identifier] = (newAssociations.length < 1 ? null : self.instance.id);
return associatedObject[associationKey];
});
update = {};
update[self.__factory.identifier] = null;
update[self.association.identifier] = null;
primaryKeys = Object.keys(this.__factory.target.primaryKeys);
primaryKeys = Object.keys(this.association.target.primaryKeys);
primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id';
updateWhere = {};
updateWhere[primaryKey] = obsoleteIds;
promises.push(this.__factory.target.update(
promises.push(this.association.target.update(
update,
updateWhere,
Utils._.extend(options, { allowNull: [self.__factory.identifier] })
Utils._.extend(options, { allowNull: [self.association.identifier] })
));
}
......@@ -76,36 +83,43 @@ module.exports = (function() {
var pkeys = Object.keys(self.instance.Model.primaryKeys)
, pkey = pkeys.length === 1 ? pkeys[0] : 'id';
primaryKeys = Object.keys(this.__factory.target.primaryKeys);
primaryKeys = Object.keys(this.association.target.primaryKeys);
primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id';
updateWhere = {};
// set the new associations
var unassociatedIds = unassociatedObjects.map(function(associatedObject) {
associatedObject[self.__factory.identifier] = self.instance[pkey] || self.instance.id;
associatedObject[self.association.identifier] = self.instance[pkey] || self.instance.id;
return associatedObject[associationKey];
});
update = {};
update[self.__factory.identifier] = (newAssociations.length < 1 ? null : self.instance[pkey] || self.instance.id);
update[self.association.identifier] = (newAssociations.length < 1 ? null : self.instance[pkey] || self.instance.id);
if (this.association.scope) {
Object.keys(this.association.scope).forEach(function (attribute) {
update[attribute] = this.association.scope[attribute];
}.bind(this));
}
updateWhere[primaryKey] = unassociatedIds;
promises.push(this.__factory.target.update(
promises.push(this.association.target.update(
update,
updateWhere,
Utils._.extend(options, { allowNull: [self.__factory.identifier] })
Utils._.extend(options, { allowNull: [self.association.identifier] })
));
}
return Utils.Promise.all(promises);
};
HasManySingleLinked.prototype.injectAdder = function(newAssociation, additionalAttributes) {
var primaryKeys = Object.keys(this.instance.Model.primaryKeys)
, primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id'
, options = additionalAttributes;
newAssociation[this.__factory.identifier] = this.instance[primaryKey];
HasManySingleLinked.prototype.injectAdder = function(newAssociation, options) {
newAssociation.set(this.association.identifier, this.instance.get(this.instance.Model.primaryKeyAttribute));
if (this.association.scope) {
Object.keys(this.association.scope).forEach(function (attribute) {
newAssociation.set(attribute, this.association.scope[attribute]);
}.bind(this));
}
return newAssociation.save(options);
};
......
......@@ -224,15 +224,19 @@ Mixin.belongsTo = singleLinked(BelongsTo);
* })
* ```
*
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {Model|string} [options.through] The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it.
* @param {string|object} [options.as] The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should provide the same alias when eager loading and when getting assocated models. Defaults to the pluralized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the target table / join table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the colum. Defaults to the name of source + primary key of source
* @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] Cascade if this is a n:m, and set null if it is a 1:m
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
* @param {Model} target
* @param {object} [options]
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {Model|string|object} [options.through] The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it.
* @param {Model} [options.through.model] The model used to join both sides of the N:M association.
* @param {object} [options.through.scope] A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model)
* @param {boolean} [options.through.unique=true] If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes)
* @param {string|object} [options.as] The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should provide the same alias when eager loading and when getting assocated models. Defaults to the pluralized name of target
* @param {string|object} [options.foreignKey] The name of the foreign key in the target table / join table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the colum. Defaults to the name of source + primary key of source
* @param {object} [options.scope] A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M)
* @param {string} [options.onDelete='SET&nbsp;NULL|CASCADE'] Cascade if this is a n:m, and set null if it is a 1:m
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
*/
Mixin.hasMany = function(targetModel, options) {
if (!(targetModel instanceof this.sequelize.Model)) {
......
......@@ -19,6 +19,7 @@ AbstractDialect.prototype.supports = {
type: false,
using: true,
},
joinTableDependent: true
};
module.exports = AbstractDialect;
......@@ -536,7 +536,7 @@ module.exports = (function() {
// check if model provided is through table
var association;
if (!as && parentAssociation && parentAssociation.through === model) {
if (!as && parentAssociation && parentAssociation.through.model === model) {
association = {as: Utils.singularize(model.tableName, model.options.language)};
} else {
// find applicable association for linking parent to this model
......@@ -874,13 +874,22 @@ module.exports = (function() {
targetJoinOn = self.quoteIdentifier(tableTarget) + '.' + self.quoteIdentifier(attrTarget) + ' = ';
targetJoinOn += self.quoteIdentifier(throughAs) + '.' + self.quoteIdentifier(identTarget);
// Generate join SQL for left side of through
joinQueryItem += joinType + self.quoteTable(throughTable, throughAs) + ' ON ';
joinQueryItem += sourceJoinOn;
if (self._dialect.supports.joinTableDependent) {
// Generate a wrapped join so that the through table join can be dependent on the target join
joinQueryItem += joinType + '(';
joinQueryItem += self.quoteTable(throughTable, throughAs);
joinQueryItem += joinType + self.quoteTable(table, as) + ' ON ';
joinQueryItem += targetJoinOn;
joinQueryItem += ') ON '+sourceJoinOn;
} else {
// Generate join SQL for left side of through
joinQueryItem += joinType + self.quoteTable(throughTable, throughAs) + ' ON ';
joinQueryItem += sourceJoinOn;
// Generate join SQL for right side of through
joinQueryItem += joinType + self.quoteTable(table, as) + ' ON ';
joinQueryItem += targetJoinOn;
// Generate join SQL for right side of through
joinQueryItem += joinType + self.quoteTable(table, as) + ' ON ';
joinQueryItem += targetJoinOn;
}
if (include.where) {
targetWhere = self.getWhereConditions(include.where, self.sequelize.literal(self.quoteIdentifier(as)), include.model, whereOptions);
......@@ -901,8 +910,8 @@ module.exports = (function() {
}
}
} else {
var left = association.associationType === 'BelongsTo' ? association.target : include.association.source
, primaryKeysLeft = association.associationType === 'BelongsTo' ? left.primaryKeyAttributes : left.primaryKeyAttributes
var left = association.associationType === 'BelongsTo' ? association.target : association.source
, primaryKeysLeft = left.primaryKeyAttributes
, tableLeft = association.associationType === 'BelongsTo' ? as : parentTable
, attrLeft = primaryKeysLeft[0]
, tableRight = association.associationType === 'BelongsTo' ? parentTable : as
......@@ -1012,10 +1021,12 @@ module.exports = (function() {
// Add WHERE to sub or main query
if (options.hasOwnProperty('where')) {
options.where = this.getWhereConditions(options.where, mainTableAs || tableName, model, options);
if (subQuery) {
subQueryItems.push(' WHERE ' + options.where);
} else {
mainQueryItems.push(' WHERE ' + options.where);
if (options.where) {
if (subQuery) {
subQueryItems.push(' WHERE ' + options.where);
} else {
mainQueryItems.push(' WHERE ' + options.where);
}
}
}
......@@ -1211,7 +1222,7 @@ module.exports = (function() {
return self.getWhereConditions(arg, tableName, factory, options, prepend);
}).join(connector);
result = '(' + result + ')';
result = result.length && '(' + result + ')' || undefined;
} else if (smth instanceof Utils.where) {
var value = smth.logic
, key = this.quoteTable(smth.attribute.Model.name) + '.' + this.quoteIdentifier(smth.attribute.fieldName)
......@@ -1272,6 +1283,8 @@ module.exports = (function() {
} else {
result = Utils.format(smth, this.dialect);
}
} else if (smth === null) {
result = '1=1';
}
return result ? result : '1=1';
......@@ -1395,14 +1408,14 @@ module.exports = (function() {
joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.target.tableName);
joins += ' ON ' + self.quoteIdentifiers(association.source.tableName + '.' + association.identifier);
joins += ' = ' + self.quoteIdentifiers(association.target.tableName + '.' + association.target.autoIncrementField);
} else if (Object(association.through) === association.through) {
joinedTables[association.through.tableName] = true;
joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.through.tableName);
} else if (Object(association.through.model) === association.through.model) {
joinedTables[association.through.model.tableName] = true;
joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.through.model.tableName);
joins += ' ON ' + self.quoteIdentifiers(association.source.tableName + '.' + association.source.autoIncrementField);
joins += ' = ' + self.quoteIdentifiers(association.through.tableName + '.' + association.identifier);
joins += ' = ' + self.quoteIdentifiers(association.through.model.tableName + '.' + association.identifier);
joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.target.tableName);
joins += ' ON ' + self.quoteIdentifiers(association.through.tableName + '.' + association.foreignIdentifier);
joins += ' ON ' + self.quoteIdentifiers(association.through.model.tableName + '.' + association.foreignIdentifier);
joins += ' = ' + self.quoteIdentifiers(association.target.tableName + '.' + association.target.autoIncrementField);
} else {
joins += ' LEFT JOIN ' + self.quoteIdentifiers(association.target.tableName);
......
......@@ -341,7 +341,7 @@ module.exports = (function() {
var replacements = {
table: this.quoteIdentifiers(tableName),
where: this.getWhereConditions(where),
where: this.getWhereConditions(where) || '1=1',
limit: !!options.limit ? ' LIMIT ' + this.escape(options.limit) : '',
primaryKeys: primaryKeys[tableName].length > 1 ? '(' + pks + ')' : pks,
primaryKeysSelection: pks
......
......@@ -15,7 +15,8 @@ SqliteDialect.prototype.supports = _.merge(_.cloneDeep(Abstract.prototype.suppor
'DEFAULT VALUES': true,
index: {
using: false
}
},
joinTableDependent: false
});
SqliteDialect.prototype.Query = Query;
......
......@@ -716,12 +716,12 @@ module.exports = (function() {
//right now, the caller (has-many-double-linked) is in charge of the where clause
Model.prototype.findAllJoin = function(joinTableName, options, queryOptions) {
var optcpy = Utils._.clone(options);
optcpy.attributes = optcpy.attributes || [this.QueryInterface.quoteTable(this.name) + '.*'];
options = optClone(options || {});
options.attributes = options.attributes || [this.QueryInterface.quoteTable(this.name) + '.*'];
// whereCollection is used for non-primary key updates
this.options.whereCollection = optcpy.where || null;
this.options.whereCollection = options.where || null;
return this.QueryInterface.select(this, [[this.getTableName(), this.name], joinTableName], optcpy, Utils._.defaults({
return this.QueryInterface.select(this, [[this.getTableName(), this.name], joinTableName], options, Utils._.defaults({
type: QueryTypes.SELECT
}, queryOptions, { transaction: (options || {}).transaction }));
};
......@@ -1742,7 +1742,7 @@ module.exports = (function() {
tableNames[include.model.getTableName()] = true;
if (include.hasOwnProperty('attributes')) {
if (include.attributes) {
include.originalAttributes = include.attributes.slice(0);
include.model.primaryKeyAttributes.forEach(function(attr) {
if (include.attributes.indexOf(attr) === -1) {
......@@ -1767,13 +1767,13 @@ module.exports = (function() {
include.as = association.as;
// If through, we create a pseudo child include, to ease our parsing later on
if (Object(include.association.through) === include.association.through) {
if (include.association.through && Object(include.association.through.model) === include.association.through.model) {
if (!include.include) include.include = [];
var through = include.association.through;
include.through = Utils._.defaults(include.through || {}, {
model: through,
as: Utils.singularize(through.tableName),
model: through.model,
as: Utils.singularize(through.model.tableName),
association: {
isSingleAssociation: true
},
......@@ -1788,6 +1788,10 @@ module.exports = (function() {
include.required = !!include.where;
}
if (include.association.scope) {
include.where = include.where ? new Util.and(include.where, include.association.scope) : include.association.scope;
}
// Validate child includes
if (include.hasOwnProperty('include')) {
validateIncludedElements.call(include.model, include, tableNames);
......
......@@ -894,9 +894,9 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
}).then(function(projects) {
expect(projects).to.have.length(1);
var project = projects[0];
expect(project.ProjectUsers).to.be.defined;
expect(project.ProjectUser).to.be.defined;
expect(project.status).not.to.exist;
expect(project.ProjectUsers.status).to.equal('active');
expect(project.ProjectUser.status).to.equal('active');
});
});
});
......@@ -1101,6 +1101,9 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
}
);
}).then(function (userGroups) {
userGroups.sort(function (a, b) {
return a.userId < b.userId ? - 1 : 1;
});
expect(userGroups[0].userId).to.equal(1);
expect(userGroups[0].isAdmin).to.be.ok;
expect(userGroups[1].userId).to.equal(2);
......@@ -1363,7 +1366,7 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
expect(associationName).not.to.equal(this.User.tableName);
expect(associationName).not.to.equal(this.Task.tableName);
var through = this.User.associations[associationName].through;
var through = this.User.associations[associationName].through.model;
if (typeof through !== 'undefined') {
expect(through.tableName).to.equal(associationName);
}
......@@ -1390,7 +1393,7 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
expect(ParanoidTask.options.paranoid).to.be.ok;
_.forEach(ParanoidUser.associations, function (association) {
expect(association.through.options.paranoid).not.to.be.ok;
expect(association.through.model.options.paranoid).not.to.be.ok;
});
});
});
......@@ -1472,7 +1475,7 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
_.each([this.UserTasks, this.UserTasks2], function (model) {
fk = Object.keys(model.options.uniqueKeys)[0];
expect(model.options.uniqueKeys[fk].fields).to.deep.equal([ 'TaskId', 'UserId' ]);
expect(model.options.uniqueKeys[fk].fields.sort()).to.deep.equal([ 'TaskId', 'UserId' ]);
});
});
......@@ -1538,8 +1541,8 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
expect(project.UserProjects).to.be.defined;
expect(project.status).not.to.exist;
expect(project.UserProjects.status).to.equal('active');
expect(project.UserProjects.data).to.equal(42);
expect(project.UserProject.status).to.equal('active');
expect(project.UserProject.data).to.equal(42);
});
});
......@@ -1556,8 +1559,8 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
expect(project.UserProjects).to.be.defined;
expect(project.status).not.to.exist;
expect(project.UserProjects.status).to.equal('active');
expect(project.UserProjects.data).not.to.exist;
expect(project.UserProject.status).to.equal('active');
expect(project.UserProject.data).not.to.exist;
});
});
});
......@@ -1841,9 +1844,9 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
User.hasMany(Group, { as: 'MyGroups', through: 'group_user'});
Group.hasMany(User, { as: 'MyUsers', through: 'group_user'});
expect(Group.associations.MyUsers.through === User.associations.MyGroups.through);
expect(Group.associations.MyUsers.through.rawAttributes.UserId).to.exist;
expect(Group.associations.MyUsers.through.rawAttributes.GroupId).to.exist;
expect(Group.associations.MyUsers.through.model === User.associations.MyGroups.through.model);
expect(Group.associations.MyUsers.through.model.rawAttributes.UserId).to.exist;
expect(Group.associations.MyUsers.through.model.rawAttributes.GroupId).to.exist;
});
it("correctly identifies its counterpart when through is a model", function () {
......@@ -1854,10 +1857,10 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
User.hasMany(Group, { as: 'MyGroups', through: UserGroup});
Group.hasMany(User, { as: 'MyUsers', through: UserGroup});
expect(Group.associations.MyUsers.through === User.associations.MyGroups.through);
expect(Group.associations.MyUsers.through.model === User.associations.MyGroups.through.model);
expect(Group.associations.MyUsers.through.rawAttributes.UserId).to.exist;
expect(Group.associations.MyUsers.through.rawAttributes.GroupId).to.exist;
expect(Group.associations.MyUsers.through.model.rawAttributes.UserId).to.exist;
expect(Group.associations.MyUsers.through.model.rawAttributes.GroupId).to.exist;
});
});
});
......@@ -2234,15 +2237,15 @@ describe(Support.getTestDialectTeaser("HasMany"), function() {
expect(Task.rawAttributes.uid).not.to.be.defined;
expect(Task.associations.tasksusers.through.rawAttributes.taskId).to.be.defined;
expect(Task.associations.tasksusers.through.rawAttributes.taskId.allowNull).to.be.false;
expect(Task.associations.tasksusers.through.rawAttributes.taskId.references).to.equal(Task.getTableName());
expect(Task.associations.tasksusers.through.rawAttributes.taskId.referencesKey).to.equal('id');
expect(Task.associations.tasksusers.through.model.rawAttributes.taskId).to.be.defined;
expect(Task.associations.tasksusers.through.model.rawAttributes.taskId.allowNull).to.be.false;
expect(Task.associations.tasksusers.through.model.rawAttributes.taskId.references).to.equal(Task.getTableName());
expect(Task.associations.tasksusers.through.model.rawAttributes.taskId.referencesKey).to.equal('id');
expect(Task.associations.tasksusers.through.rawAttributes.uid).to.be.defined;
expect(Task.associations.tasksusers.through.rawAttributes.uid.allowNull).to.be.false;
expect(Task.associations.tasksusers.through.rawAttributes.uid.references).to.equal(User.getTableName());
expect(Task.associations.tasksusers.through.rawAttributes.uid.referencesKey).to.equal('id');
expect(Task.associations.tasksusers.through.model.rawAttributes.uid).to.be.defined;
expect(Task.associations.tasksusers.through.model.rawAttributes.uid.allowNull).to.be.false;
expect(Task.associations.tasksusers.through.model.rawAttributes.uid.references).to.equal(User.getTableName());
expect(Task.associations.tasksusers.through.model.rawAttributes.uid.referencesKey).to.equal('id');
});
it('works when taking a column directly from the object', function () {
......
......@@ -217,7 +217,6 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
User.find(1).success(function(user){
Project.find(1).success(function(project){
user.setProjects([project]).success(function(){
User.find(2).success(function(user){
Project.find(2).success(function(project){
user.setProjects([project]).success(function(){
......@@ -246,6 +245,6 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
});
});
});
})
})
})
});
});
});
......@@ -133,7 +133,7 @@ describe(Support.getTestDialectTeaser("Self"), function() {
});
}).then(function () {
return this.john.getChildren().on('sql', function(sql) {
var whereClause = sql.split('WHERE')[1]; // look only in the whereClause
var whereClause = sql.split('FROM')[1]; // look only in the whereClause
expect(whereClause).to.have.string('preexisting_child');
expect(whereClause).to.have.string('preexisting_parent');
});
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!