strongloop – Loopback模型中的动态属性或聚合函数

前端之家收集整理的这篇文章主要介绍了strongloop – Loopback模型中的动态属性或聚合函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我如何在Loopback模型中使用聚合函数?如果我有一个由MysqL数据库支持的模型,我可以让Model1与Model2具有hasMany关系(具有给定的数字属性),并且在Model1中有一个属性可以从Model2中获取该字段的SUM吗?
  1.  
  2. {
  3. "Model1" : {
  4. "Relations" : {
  5. "model2s" : {
  6. "type": "hasMany","model": "Model2","foreignKey": "model1Id"
  7. }
  8. },"Properties" : {
  9. "total" : {
  10. "type": "Number"
  11. [SUM of Model2 'amount' field]
  12. }
  13. }
  14. },"Model2" : {
  15. "Relations" : {
  16. "model1s" : {
  17. "type": "belongsTo","model": "Model1","Properties" : {
  18. "amount" : {
  19. "type": "Number"
  20. }
  21. }
  22. }
  23. }
  24.  

在另一个问题上,将条件放入模型的正确方法是什么,以便getter返回的值取决于某个表达式?我想从关系中返回一个值(如果存在),否则返回主模型上存在的值.

我试过这个(伪代码):

  1.  
  2. module.exports = function(MyModel) {
  3. MyModel.on('attached',function() {
  4. var app = MyModel.app;
  5.  
  6. MyModel.getter['total'] = function() {
  7. return (this.model1Id ? this.model1.total : this.total);
  8. };
  9. });
  10.  
  11. };

但是,我最终得到一个RangeError:超出最大调用堆栈大小错误(类似于this question中所述).我假设这是因为它一遍又一遍地递归调用getter,但我不确定解决问题的方法.

提前致谢…

AFAIK环回目前不支持聚合函数/属性.请 open a github issue跟踪此功能请求.

请注意,访问相关模型的数据是异步操作,因此无法可靠地实现属性(getter函数)来返回聚合结果.

这是一个模拟显示如何正确实现计算总计:

  1. MyModel.prototype.getTotal = function(cb) {
  2. if (!this.model1Id) {
  3. // No related model,return the total from this model.
  4. return cb(null,this.total);
  5. }
  6.  
  7. // Fetch the related model and return its total
  8. this.model1(function(err,model1) {
  9. if (err)
  10. cb(err);
  11. else
  12. cb(null,model1.total);
  13. });
  14. }

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 a RangeError: Maximum call stack size exceeded error

正如我在你所链接的答案中解释的那样,this.total调用你的自定义getter函数,该函数调用this.total等等.

解决方案是从内部数据对象中读取值:

  1. MyModel.getter['total'] = function() {
  2. return this.__data.total;
  3. };

猜你在找的设计模式相关文章