add count to relations

Signed-off-by: Jaka Hudoklin <jakahudoklin@gmail.com>
This commit is contained in:
Jaka Hudoklin 2014-08-12 14:44:33 +02:00
parent c3f7a7acb5
commit 0d44cdc573
2 changed files with 23 additions and 0 deletions

View File

@ -138,6 +138,7 @@ function defineScope(cls, targetClass, name, params, methods, options) {
f.build = build; f.build = build;
f.create = create; f.create = create;
f.destroyAll = destroyAll; f.destroyAll = destroyAll;
f.count = count;
for (var i in definition.methods) { for (var i in definition.methods) {
f[i] = definition.methods[i].bind(self); f[i] = definition.methods[i].bind(self);
} }
@ -183,6 +184,13 @@ function defineScope(cls, targetClass, name, params, methods, options) {
cls['__delete__' + name] = fn_delete; cls['__delete__' + name] = fn_delete;
var fn_count = function (cb) {
var f = this[name].count;
f.apply(this[name], arguments);
};
cls['__count__' + name] = fn_count;
/* /*
* Extracting fixed property values for the scope from the where clause into * Extracting fixed property values for the scope from the where clause into
* the data object * the data object
@ -240,6 +248,11 @@ function defineScope(cls, targetClass, name, params, methods, options) {
targetClass.destroyAll(where, cb); targetClass.destroyAll(where, cb);
} }
function count(cb) {
var where = (this._scope && this._scope.where) || {};
targetClass.count(where, cb);
}
return definition; return definition;
} }

View File

@ -538,6 +538,16 @@ describe('relations', function () {
}); });
}); });
it('should find count of records on scope - scoped', function (done) {
Category.findOne(function (err, c) {
c.productType = 'tool'; // temporary, for scoping
c.products.count(function(err, count) {
count.should.equal(1);
done();
});
});
});
it('should delete records on scope - scoped', function (done) { it('should delete records on scope - scoped', function (done) {
Category.findOne(function (err, c) { Category.findOne(function (err, c) {
c.productType = 'tool'; // temporary, for scoping c.productType = 'tool'; // temporary, for scoping