我如何在Loopback模型中使用聚合函数?如果我有一个由MysqL数据库支持的模型,我可以让Model1与Model2具有hasMany关系(具有给定的数字属性),并且在Model1中有一个属性可以从Model2中获取该字段的SUM吗?
- {
- "Model1" : {
- "Relations" : {
- "model2s" : {
- "type": "hasMany","model": "Model2","foreignKey": "model1Id"
- }
- },"Properties" : {
- "total" : {
- "type": "Number"
- [SUM of Model2 'amount' field]
- }
- }
- },"Model2" : {
- "Relations" : {
- "model1s" : {
- "type": "belongsTo","model": "Model1","Properties" : {
- "amount" : {
- "type": "Number"
- }
- }
- }
- }
在另一个问题上,将条件放入模型的正确方法是什么,以便getter返回的值取决于某个表达式?我想从关系中返回一个值(如果存在),否则返回主模型上存在的值.
我试过这个(伪代码):
- module.exports = function(MyModel) {
- MyModel.on('attached',function() {
- var app = MyModel.app;
- MyModel.getter['total'] = function() {
- return (this.model1Id ? this.model1.total : this.total);
- };
- });
- };
但是,我最终得到一个RangeError:超出最大调用堆栈大小错误(类似于this question中所述).我假设这是因为它一遍又一遍地递归调用getter,但我不确定解决问题的方法.
提前致谢…
AFAIK环回目前不支持聚合函数/属性.请
open a github issue跟踪此功能请求.
请注意,访问相关模型的数据是异步操作,因此无法可靠地实现属性(getter函数)来返回聚合结果.
这是一个模拟显示如何正确实现计算总计:
- MyModel.prototype.getTotal = function(cb) {
- if (!this.model1Id) {
- // No related model,return the total from this model.
- return cb(null,this.total);
- }
- // Fetch the related model and return its total
- this.model1(function(err,model1) {
- if (err)
- cb(err);
- else
- cb(null,model1.total);
- });
- }
On a separate matter,what is the correct way to put a conditional in a model,so that the value returned by a getter depends on some expression?
I end up getting aRangeError: Maximum call stack size exceeded
error
正如我在你所链接的答案中解释的那样,this.total调用你的自定义getter函数,该函数又调用this.total等等.
解决方案是从内部数据对象中读取值:
- MyModel.getter['total'] = function() {
- return this.__data.total;
- };