Kishan Rajdev
Kishan Rajdev

Reputation: 1967

sailJs writing mysql custom queries

I have created an API in sailJs. In which i am able to find the data from the database using Ids, by making get request

sails generate api dentist 

I want to write my custom queries to fetch the data. I am not able to figure out how to do the same.

I can do it by Model.query() but unable to figure out the way

here is my model file

module.exports = {
tableName: 'user',
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
name:{type: 'string'}
}
};

Need help in this.

Upvotes: 2

Views: 103

Answers (2)

krakig
krakig

Reputation: 1555

There are 2 ways of doing the queries : Either you do as you mentioned, using the query syntax, and in that case, you don't care which model you use, it works for everything.

Or you can use the ORM that waterline provides :

Dentist.find({ where: { name: 'theNameHere' }, limit: 10});

In that case, you need to use the specific model that will contain the answer. You can check the docs here : http://sailsjs.org/documentation/concepts/models-and-orm/query-language

Upvotes: 2

Kishan Rajdev
Kishan Rajdev

Reputation: 1967

Have figured out the answer, we can write queries in controller.

Here is the way to do it,

module.exports = {
 /*
    function to return  select data
 */
 getdata: function(req,res) {
    var key = req.body.name+"%";
    var post = [];
    post.push(key);
    Dentist.query('select * from where name like ? limit 10',post,function(err,result){
        return (!err)? res.ok(result) : res.ok({error:'error occured'});
    });
 }
}

One more thing i have noticed here is model of any module/api can be used to call the query.

Upvotes: 2

Related Questions