Sqlite.swift 创建动态复杂查询
Sqlite.swift create dynamic complex queries
我有 1 个 table 多列。
在应用程序上,我们期待添加 4 个动态过滤器,例如(猫、大小、颜色、形状)。
我们知道我们可以像这样为 sqllite 创建一个过滤器:
user = user.select(name)
.filter((color == "Blue") && (size = "Big") && (cat="a") && (shape="round"))
.order(name.asc, name) // ORDER BY "email" DESC, "name"
.limit(5, offset: 0)
但是如果过滤器会发生什么,假设我们想要搜索所有颜色的颜色。那么,
.filter((color == "?????") && (size = "Big") && (cat="a") && (shape="round"))
关于如何为这种情况创建动态过滤器的任何想法?
filter()
方法接受一个 Expression<Bool>
参数,
可以使用逻辑运算符 &&
、||
等动态创建复合表达式
简单示例:
// Start with "true" expression (matches all records):
var myFilter = Expression<Bool>(value: true)
// Dynamically add boolean expressions:
if shouldFilterColor {
myFilter = myFilter && (color == "Blue")
}
if shouldFilterSize {
myFilter = myFilter && (size == "Big")
}
// ... etc ...
// Use compound filter:
query = user.select(name)
.filter(myFilter)
.order(name.asc, name)
.limit(5, offset: 0)
我有 1 个 table 多列。 在应用程序上,我们期待添加 4 个动态过滤器,例如(猫、大小、颜色、形状)。
我们知道我们可以像这样为 sqllite 创建一个过滤器:
user = user.select(name)
.filter((color == "Blue") && (size = "Big") && (cat="a") && (shape="round"))
.order(name.asc, name) // ORDER BY "email" DESC, "name"
.limit(5, offset: 0)
但是如果过滤器会发生什么,假设我们想要搜索所有颜色的颜色。那么,
.filter((color == "?????") && (size = "Big") && (cat="a") && (shape="round"))
关于如何为这种情况创建动态过滤器的任何想法?
filter()
方法接受一个 Expression<Bool>
参数,
可以使用逻辑运算符 &&
、||
等动态创建复合表达式
简单示例:
// Start with "true" expression (matches all records):
var myFilter = Expression<Bool>(value: true)
// Dynamically add boolean expressions:
if shouldFilterColor {
myFilter = myFilter && (color == "Blue")
}
if shouldFilterSize {
myFilter = myFilter && (size == "Big")
}
// ... etc ...
// Use compound filter:
query = user.select(name)
.filter(myFilter)
.order(name.asc, name)
.limit(5, offset: 0)