【发布时间】:2016-06-22 19:47:27
【问题描述】:
using-mix-of-and-and-or-clause-in-sails-and-waterline
这两个问题,处理在 or 中有 n 个字段,但 AND 中有唯一字段,这只是在放置属性名称时隐式添加的,它们被转换为 ANDS,如下所示:
{attribute1: 'valueToMatch', or: [{attribute2: {contains: 'someWord'}}, {attribute3: {contains: 'someWord'}}]
如果 AND (attribute1) 只使用一次,这很好,但如果您想要满足 2 个或多个条件 (AND) 并且其中包含可选条件 (OR),这无济于事
有办法吗?
假设我有一个像这样的用户模型
let User = {
attributes:{
firstName: {type: 'string'},
lastName: {type: 'string'}
}
};
并且我希望能够搜索某个字符串是否至少在其中一个字段 (OR) 中,假设我传递了一个可以是名字或姓氏的字符串,这可以使用或语法
let searchString = 'John'
let results = yield User.find({or: [
{firstName: {contains: searchString}]},
{lastName: {contains: searchString}]}
});
到目前为止一切都很好,但是如果我的搜索字符串包含更多单词,可以说
let searchString = 'John Doe'
除非有包含完整字符串的 firstName 或 lastName 记录,否则它将不起作用。
我知道有一些 hacky workarouds,比如有一个 fullName 属性,可以在创建和更新时根据其他属性生成并搜索它,但由于我正在复制数据,这样我就不会能够在 firstName 之前使用 lastName 进行搜索,这不是一个完美的解决方案。我也可以拆分 searchString 并将每个单词添加到 OR 数组中,不知何故更好,但我的结果不会被过滤得足够多,更不用说排名了,所以它也不是一个完美的解决方案,最后我可以做一个原始查询。 ...
所以真正的问题是如何在水线中进行 AND 以与 or 一起使用以进一步细化,因为对我而言,AND 是根据传递的属性名称标准生成的。
有这样的吗?
// Lets assume i've splitted the searchString
let string1 = 'John';
let string2 = 'Doe'
let results = yield User.find({
and: [
{or: [
{firstName: {contains: string1}},
{lastName: {contains: string1}}
]
},
{or: [
{firstName: {contains: string2}},
{lastName: {contains: string2}}
]
},
]
});
或者我在这里有什么选择?
【问题讨论】: