Sqlite.swift创建动态复杂查询 [英] Sqlite.swift create dynamic complex queries

查看:199
本文介绍了Sqlite.swift创建动态复杂查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1个具有多列的表. 在应用程序上,我们期待添加4个动态过滤器,例如(猫,大小,颜色,形状).

I have 1 table with multiple columns. On the app, we are looking forward to add 4 dynamic filters like (cat, size, color,shape).

我们知道我们可以像这样为sqllite创建过滤器:

We know we can create a filter to sqllite like so:

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)

但是,如果使用滤镜,会发生什么情况呢?假设对于颜色,我们要搜索所有颜色.然后,

But what happens if a filter, let's say that for color we want to search for all colors. Then,

.filter((color == "?????") && (size = "Big") && (cat="a") && (shape="round"))

关于如何为这种情况创建动态过滤器的任何想法?

Any ideas on how to create dynamic filters for this case?

推荐答案

filter()方法采用Expression<Bool>自变量, 可以使用逻辑运算符&&||等动态创建复合表达式.

The filter() method takes an Expression<Bool> argument, and compound expressions can be created dynamically with the logical operators &&, ||, etc.

简单的例子:

// 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)

这篇关于Sqlite.swift创建动态复杂查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆