Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dynamic search parameters with Sequelize.js

I'm trying to follow the Sequelize tutorial on their website.

I have reached the following line of code.

Project.findAll({where: ["id > ?", 25]}).success(function(projects) {
  // projects will be an array of Projects having a greater id than 25
})

If I tweak it slightly as follows

Project.findAll({where: ["title like '%awe%'"]}).success(function(projects) {
    for (var i=0; i<projects.length; i++) {
        console.log(projects[i].title + " " + projects[i].description);
    }
});

everything works fine. However when I try to make the search parameter dynamic as follows

Project.findAll({where: ["title like '%?%'", 'awe']}).success(function(projects) {
    for (var i=0; i<projects.length; i++) {
        console.log(projects[i].title + " " + projects[i].description);
    }
});

It no longer returns any results. How can I fix this?

like image 327
Hoa Avatar asked Feb 17 '12 00:02

Hoa


4 Answers

Now on Sequelize you can try this

{ where: { columnName: { $like: '%awe%' } } }

See http://docs.sequelizejs.com/en/latest/docs/querying/#operators for updated syntax

like image 170
Javier Cornejo Alfaro Avatar answered Nov 10 '22 14:11

Javier Cornejo Alfaro


I think you would do that like this:

where: ["title like ?", '%' + 'awe' + '%']

So if you were doing this with an actual variable you'd use:

Project.findAll({where: ["title like ?", '%' + x + '%']}).success(function(projects) {
    for (var i=0; i<projects.length; i++) {
        console.log(projects[i].title + " " + projects[i].description);
    }
});
like image 35
Paul Avatar answered Nov 10 '22 13:11

Paul


Please try this code

const Sequelize = require('sequelize');
const Op = Sequelize.Op;
{ where: { columnName: { [Op.like]: '%awe%' } } }
like image 6
Manoj Rana Avatar answered Nov 10 '22 15:11

Manoj Rana


I would do it in this way:

Project.findAll({where: {title: {like: '%' + x + '%'}, id: {gt: 10}}).success(function(projects) {
  for (var i=0; i<projects.length; i++) {
    console.log(projects[i].title + " " + projects[i].description);
  }
});

In this way you can have nicely more WHERE clausas

like image 4
mPrinC Avatar answered Nov 10 '22 13:11

mPrinC