How would I go about using aggregate functions in Loopback models? If I have a model backed by a mysql database, could I have Model1 with a hasMany relation to Model2 (with a given numeric property), and have a property in Model1 that grabs the SUM of that field from Model2?
{ "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", "foreignKey": "model1Id" } }, "Properties" : { "amount" : { "type": "Number" } } } }
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 want to return a value from a relation if it exists, otherwise return the one that exists on the primary model.
I have tried this (pseudocode):
module.exports = function(MyModel) { MyModel.on('attached', function() { var app = MyModel.app; MyModel.getter['total'] = function() { return (this.model1Id ? this.model1.total : this.total); }; }); };
However, I end up getting a RangeError: Maximum call stack size exceeded
error (similar to what is noted in this question). I'm assuming that is because it recursively calls the getter over and over, but I'm not sure of the way to resolve the issue.
Thanks in advance...
this.__data
— and if I spit outthis
to the console, I don't see a key like that. Am I using it in the wrong scope or something? I'm doing it in the context that I listed above (simply replacing what I had in the getter function with calls to this.__data as you indicated); is that not correct? – Whack