在不遍历对象的所有实例的情况下在环回中获取属性的 sum()
Getting sum() of an attribute in loopback without looping through all instances of the object
我有一个模型 DummyModel
,它具有属性 attOne
、attTwo
和 attThree
。
要获取attOne
的所有实例,可以使用-
DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} });
以上查询或多或少对应于MySQL
查询-
select attOne from DummyModel where attTwo = 'someValue'
但是,我需要找到从上述查询返回的所有 attOne 值的总和。也就是说,MySQL 相当于 -
select sum(attOne) from DummyModel where attTwo = 'someValue'
我读到环回不支持聚合函数(即 groupby
)。但是有没有办法得到sum(attOne)
?
我知道一种方法是获取对象,然后遍历所有实例并添加它。
我想知道是否有任何预先存在的环回方法可以做同样的事情。
假设这段代码
f = DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} });
returns 这样的数组
[
{attTwo: 'someValue' ,attOne: 1}
{attTwo: 'otherValue',attOne: 1}
]
您可以使用 reduce function 将函数应用于所有元素
var sum = f.reduce(function(last, d) {return d.attOne + last},0);
这是工作代码
DummyModel = {
find: function(a) {
return [{
attTwo: 'someValue',
attOne: 1
}, {
attTwo: 'otherValue',
attOne: 2
}];
}
}
f = DummyModel.find({
where: {
attTwo: 'someValue'
},
fields: {
attOne: true
}
});
sum = f.reduce(function(last, d) {
return d.attOne + last;
}, 0);
alert(sum);
我有一个模型 DummyModel
,它具有属性 attOne
、attTwo
和 attThree
。
要获取attOne
的所有实例,可以使用-
DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} });
以上查询或多或少对应于MySQL
查询-
select attOne from DummyModel where attTwo = 'someValue'
但是,我需要找到从上述查询返回的所有 attOne 值的总和。也就是说,MySQL 相当于 -
select sum(attOne) from DummyModel where attTwo = 'someValue'
我读到环回不支持聚合函数(即 groupby
)。但是有没有办法得到sum(attOne)
?
我知道一种方法是获取对象,然后遍历所有实例并添加它。
我想知道是否有任何预先存在的环回方法可以做同样的事情。
假设这段代码
f = DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} });
returns 这样的数组
[
{attTwo: 'someValue' ,attOne: 1}
{attTwo: 'otherValue',attOne: 1}
]
您可以使用 reduce function 将函数应用于所有元素
var sum = f.reduce(function(last, d) {return d.attOne + last},0);
这是工作代码
DummyModel = {
find: function(a) {
return [{
attTwo: 'someValue',
attOne: 1
}, {
attTwo: 'otherValue',
attOne: 2
}];
}
}
f = DummyModel.find({
where: {
attTwo: 'someValue'
},
fields: {
attOne: true
}
});
sum = f.reduce(function(last, d) {
return d.attOne + last;
}, 0);
alert(sum);