Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perform COUNT and GROUP BY in Waterline?

I want to perform this query in Waterline:

SELECT priority, count(*) AS Num FROM Ticket GROUP BY priority

I dont know how the "countByName" function works and i dont find a proper example or explanation.

I also tried to call it with

Model.query('SELECT ...')

but that just returns undefined.

like image 414
Spyse Avatar asked Nov 08 '13 16:11

Spyse


1 Answers

I think that Model.query isn't going to return anything, it should be given a callback. It should look more like:

Model.query("SELECT priority, COUNT(*) as num FROM ticket GROUP BY priority", 
  function(error, counts) { 
    if(error) console.log(error);
    // Do something with the results here.        
    console.log(counts); 
  });

Edit: Upon some research you can't use count, but you can use other calculations with a group by in Sails but the syntax doesn't appear to be well documented.:

Something.find({ groupBy: [ 'keyfield' ], sum: [ 'totalAmt' ] })
  .done(function(error, response) {
    console.log(response);
  });
like image 83
sfb Avatar answered Nov 15 '22 08:11

sfb