[英]Bookshelf.js Where Like Dynamic Input
I am trying to create a autocomplete search using Express/Bookshelf/Awesomeplete. 我正在尝试使用Express / Bookshelf / Awesomeplete创建自动完成搜索。
I am stuck in trying to figure out out to pass the search terms to Bookshelf using a Where Like query like such, that I am converting from PHP/MYSQL. 我一直试图找出使用类似Where Like的查询将搜索词传递到Bookshelf的方法,这是我从PHP / MYSQL转换而来的。
$query = mysql_escape_string($_REQUEST['query']);
$query = htmlentities($query);
SELECT SID, schoolName FROM schools WHERE schoolName LIKE '%$query%'
Here is what I have so far. 这是我到目前为止所拥有的。
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'});
});
If I change the above to: 如果我将以上内容更改为:
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'});
});
The Bookshelf query functions as I need it to, but I want the query parameter to be dynamic. Bookshelf查询可以按我的需要运行,但我希望查询参数是动态的。 I have tried a bunch of permutations, but can't get it to work. 我尝试了很多排列,但是无法正常工作。
From my comment and your validation, it looks like the following works. 根据我的评论和您的验证,它看起来像以下作品。
Basically you want to attach the '%' to the searched value before passing it into the .query
LIKE clause. 基本上,您需要在将'%'附加到.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'});
});
Happy Coding. 编码愉快。 Gary. 加里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.