我的应用程序中有人名的搜索框。候选人的姓名存储为firstName,然后存储为lastName。当我搜索应用程序时,应用程序输入提交对ajax函数的调用,其中我有这段代码。
filters.where = {
$or: ['firstName', 'lastName', 'email'].map((item) =>
({[item]: {[queryClause]: `%${query}%`}}))
};
const scope = req.query.list;
const candidates = await CandidateModel.scope(scope).findAll(filters);
因此,如果我输入搜索框" John",它会找到候选人,如果我输入单词" Smith"它会找到候选人。
问题是,如果我输入全名" John Smith"它不会出现,因为查询正在检查是否" John Smith"等于" John",即名字,或者" John Smith"等于"史密斯",姓氏。它与这些中的任何一个都不相同。
有没有办法通过sequalize中的组合字段进行过滤,因此它会测试查询是否与firstName和lastName字段组合在一起?
答案 0 :(得分:8)
使用以下内容在此表单中按全名搜索" firstName lastName"
Sequelize.where(Sequelize.fn("concat", Sequelize.col("firstName"), ' ', Sequelize.col("lastName")), {
$ilike: '%john smith%'
})
这样做可以解决名字或姓氏问题可能有空格的问题。
答案 1 :(得分:1)
似乎您可能需要拆分查询输入并搜索传入条件的所有字段。例如:
var queryClause ='John Smith';
filters.where = {
$or: _.flatten(_.map(['firstName', 'lastName', 'email'], function(){
return _.map(queryClause.split(' '), function(q){
return {[item]: { $like : '%'+q+'%'}}
})
}))
}
会输出如下内容:
{
"where": {
"$or": [{
"firstName": {
"$like": "%John%"
}
}, {
"firstName": {
"$like": "%Smith%"
}
}, {
"lastName": {
"$like": "%John%"
}
}, {
"lastName: {
"$like": "%Smith%"
}
},
{
"email": {
"$like": "%John%"
}
},
{
"email": {
"$like": "%Smith%"
}
}]
}
}
- 顺便说一下在上面的示例代码中使用lodash
答案 2 :(得分:0)
我无法找到如何使用sequelize本地执行此操作,但您始终可以使用原始查询
sequelize.query('SELECT * FROM candidates where (firstName+lastName) like query OR email like query', { model: Candidate})
.then(function(projects){
// Each record will now be a instance of Candidate
})