Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LoopBack "group by" ability with mySQL?

I'm new to LoopBack, and I seem to be missing something. I've heard so much about StrongLoop and LoopBack, I find it hard to believe this doesn't exist.

My case: I'm looking to count the amount of events with each different severity.

A table for example:

EventID | Severity

1 | 2

2 | 2

3 | 4

4 | 3

5 | 3

6 | 5

7 | 1

8 | 2

Now I want to count the amount of events and group them by severity, so I get something like this JSON back:

{1:1, 2:3, 3:2, 4:1, 5:1} *(severity:count)*

With SQL it's quite simple, just use "SELECT severity, count(severity) FROM events GROUP BY severity".

I have researched this for a while, and still can't believe this simple thing can't be done with LoopBack!

Any solution? Or maybe an article to point me to?

Thanks in advance!

like image 724
Finkel Avatar asked Feb 17 '16 12:02

Finkel


1 Answers

Well Loopback ORM as of this moment doesn't have support for it completely but you can always use the MySQL driver directly:

YourModel.dataSource.connector.query('SELECT severity, count(severity) FROM events GROUP BY severity', (err, results) => {
   //...
});

But if you want to be database agnostic, you can do it in Javascript with Lodash:

YourModel.find({ fields: 'severity' }).then(rows => {
  const results = _.mapValues(_.groupBy(rows, severity), 'length');
  //...
});
like image 99
Farid Nouri Neshat Avatar answered Oct 17 '22 18:10

Farid Nouri Neshat