Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build complex Model.find request

I am building an API using Sails.js

At the moment I am executing raw sql requests to find a list of Status :

        Status.query("SELECT Status.* FROM Status,User where Status.user = User.id and User.isPrivate = false group by status.id  order by status.id desc limit "+limit+" offset "+offset, function(err, status) {
            if(err) return next(err);


            console.log(status)
            console.log(res)
            res.json(200,status);
        });

2 problems :

1- It is raw SQL so i will not be able to switch to Mango or anything else because my code is linked to my database choice 2- Model.find automatically load relationships (here Status.user and Status.find) and raw sql only load the ID

2- I am looking for the syntax to build 'complex' requests using Model.Find to let me get the exact same result than the raw sql one and also do things like

AND:
[
    {
    or:
        [ 
            {a=1,b=2},
            {a=2,b=1}
        ]
    },
    {c=6}
]
like image 534
Adel 'Sean' Helal Avatar asked Dec 10 '25 20:12

Adel 'Sean' Helal


1 Answers

Ok i successfully found how to do !

So the goal was to convert this request :

Status.query("SELECT Status.* FROM Status,User where Status.user = User.id and User.isPrivate = false group by status.id  order by status.id desc limit "+limit+" offset "+offset, function(err, status) {
            if(err) return next(err);


            console.log(status)
            console.log(res)
            res.json(200,status);
        });

To a Model.find request using Sails.js syntax in state of mysql. Here you go : (without pagination but its easy to find how to do)

Status.find({}).populate('user',{isPrivate:'false'}).exec(function(status,err){
                if(err) return next(err);


                console.log(status)
                console.log(res)
                res.json(200,status);
            });

Have fun!

like image 164
Adel 'Sean' Helal Avatar answered Dec 13 '25 09:12

Adel 'Sean' Helal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!