[英]Bookshelf.js Where Like Dynamic Input
我正在尝试使用Express / Bookshelf / Awesomeplete创建自动完成搜索。
我一直试图找出使用类似Where Like的查询将搜索词传递到Bookshelf的方法,这是我从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查询可以按我的需要运行,但我希望查询参数是动态的。 我尝试了很多排列,但是无法正常工作。
根据我的评论和您的验证,它看起来像以下作品。
基本上,您需要在将'%'附加到.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'});
});
编码愉快。 加里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.