davron
davron

Reputation: 39

select from MySql db from sails in native query

i want to get result: group + count of messages which belong to the current group for example:

webdevelopment - 34 messages

How can I achieve the same result without performing _.each

how i can to get the result one Query I used MySql, my code something like this

 Group.find().exec(function (err, groups) {
        if (err)
            return next(err);
        _.each(groups, function (grouper) {
            Messages.count({
                groupId : grouper.groupId,
            }).exec(function (err, found) {
                console.log(grouper.groupName + ' - ' + found + ' messages.');

            });
        });
    });

my module somethink like this

module messages

module.exports = {
  attributes: {
    id:{
         type: 'integer',
         primaryKey: true,
         autoIncrement: true
      },
    groupId:{
        type:'int'
    }
  }
};

module Group

module.exports = {
  attributes: {
  id:{
     type: 'integer',
     primaryKey: true,
     autoIncrement: true
  },
  groupName:{
    type:'string'
  }

  }
};

Upvotes: 0

Views: 2266

Answers (2)

TheLebDev
TheLebDev

Reputation: 531

As of Sails v1, Model.query has been deprecated, instead use sails.sendNativeQuery(queryString, paramArray)

Upvotes: 1

myusuf
myusuf

Reputation: 12240

You need to write the SQL query that gives the desired result. Lets say the query is:

var myQuery = "Select ... from ...";

Now you can execute the query using query method of the Model like so:

Group.query(myQuery, function(err, res) {
  /* use res.rows to get the result */
});

It does not matter which model you use when using query method.

Upvotes: 2

Related Questions