[英]Is it possible to use orWhereRaw more than once in a bookshelf.js query?
I am trying to create a function which would allow the user to search by multiple parameters. 我正在尝试创建一个函数,该函数将允许用户通过多个参数进行搜索。 Here is the code.
这是代码。
async function searchUsers(searchText) {
if(isNaN(searchText)){
searchText = "'%" + searchText + "%'";
} else {
searchText = searchText;
}
let results = await User.query({whereRaw: ' (`firstName` LIKE ' + searchText , orWhereRaw: '`lastName` LIKE ' + searchText
, orWhereRaw: '`username` LIKE' + searchText, orWhereRaw: '`providerId` =' + searchText + ")"}).fetchAll();
return results.toJSON();
}
Now when running this function, this is what I see in my command line. 现在,当运行此功能时,这就是我在命令行中看到的内容。
sql: 'select `users`.* from `users` where (`firstName` LIKE 1 or `providerId` =1)' }
As you can plainly see the query is only including firstName and providerId. 如您所见,查询仅包含firstName和providerId。 There is no mention of lastName or username.
没有提及lastName或用户名。
How can I include all parameters? 如何包含所有参数?
Your error is using the same key twice in the same object. 您的错误是在同一对象中两次使用相同的键。 The second overwrites the first.
第二个覆盖第一个。
assert.deepEqual({ a: true }, { a: false, a: true });
Use a linter to prevent this kind of problem. 用短绒棉防止这种问题。
Solution: 解:
let results = await User.query(queryBuilder => queryBuilder
.whereRaw('`firstName` LIKE ?', searchText)
.orWhereRaw('`lastName` LIKE ?', searchText)
.orWhereRaw('`username` LIKE ?', searchText)
.orWhereRaw('`providerId` = ?', searchText)
).fetchAll();
Although that wont produce the parentheses you want. 虽然那样不会产生您想要的括号。 You don't need any raw queries for what you're doing.
您无需对自己的工作进行任何原始查询。 It's pretty standard stuff.
这是很标准的东西。
let results = await User
.where('firstName', 'like', searchText)
.orWhere(function () {
this.where('firstName', 'like', searchText)
.orWhere('lastName' 'like', searchText)
.orWhere('username', 'like', searchText)
.orWhere('providerId', searchText)
});
)
).fetchAll();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.