Bookshelf.js喜欢动态输入

时间:2018-01-12 22:24:02

标签: javascript knex.js bookshelf.js

我正在尝试使用Express / Bookshelf / Awesomeplete创建自动完成搜索。

我一直试图找出将搜索词传递给Bookshelf使用类似Where Where的查询,我正在从PHP / MYSQL转换。

$query = mysql_escape_string($_REQUEST['query']);
$query = htmlentities($query);  
SELECT SID, schoolName FROM schools WHERE schoolName LIKE '%$query%'

这是我到目前为止所拥有的。

var terms = req.params.search;

new Model.School()
//This is the part that I can't get to work.
.query('where', 'schoolName', 'LIKE', '%'?'%',[terms])
.fetchAll({columns: ['SID', 'schoolName']})
.then(function (schools) {
   console.log(schools);
   var schools = schools.toJSON();
   res.json(schools);
 })
 .catch(function (error) {
    res.json({'message':'An error occured in your search'});
 });

如果我将上述内容更改为:

new Model.School()
.query('where', 'schoolName', 'LIKE', '%american%')
.fetchAll({columns: ['SID', 'schoolName']})
.then(function (schools) {
   console.log(schools);
   var schools = schools.toJSON();
   res.json(schools);
 })
 .catch(function (error) {
    res.json({'message':'An error occured in your search'});
 });

Bookshelf查询功能正如我所需,但我希望查询参数是动态的。我尝试了一堆排列,但无法让它发挥作用。

1 个答案:

答案 0 :(得分:2)

从我的评论和验证中看起来如下工作。

基本上你想要附上'%'在将其传递到.query LIKE子句之前搜索到的值。

var terms = "%"+req.params.search+"%";

new Model.School()
.query('where', 'schoolName', 'LIKE', terms)
.fetchAll({columns: ['SID', 'schoolName']})
.then(function (schools) {
   console.log(schools);
   var schools = schools.toJSON();
   res.json(schools);
 })
 .catch(function (error) {
    res.json({'message':'An error occured in your search'});
 });

快乐编码。加里。