Richa Dhanuka
Richa Dhanuka

Reputation: 21

Distinct query on loopback-connector-mysql

I'm using loopback and i want to fetch all unique location name from Job model. I've tried

Job.find({
    where: {
        location:distinct
    }
});

But it doesn't work.

Upvotes: 0

Views: 1627

Answers (1)

xangy
xangy

Reputation: 1205

There is no distinct keyword in Loopback right now. But I believe there exist DISTINCT keyword to query distinct columns in MySQL. So you can use this method to execute native sql query. Check the docs here. Below is a sample code on how to use it.

module.exports = function(Job) {
    Job.distinctLocations = function(byId, cb){
        var ds = Job.dataSource;
        var sql = "SELECT DISTINCT location FROM Job";  //here you write your sql query.
        ds.connector.execute(sql, byId, function(err, jobs) {
            if (err) console.error(err);
            cb(err, jobs);
        });
    };
    Job.remoteMethod(
        'distinctLocations',
        {
            http: {verb: 'get'},
            description: "Get distinct locations for the jobs.",
            returns: {arg: 'locations', type: 'object', root: true}
        }
    );
};

Upvotes: 1

Related Questions