【问题标题】:Query builder dbflow conditional query查询生成器 dbflow 条件查询
【发布时间】:2016-09-05 03:05:18
【问题描述】:
如何根据特定条件构建查询。
我试过这样做
QueryBuilder builder = SQlite.Select().from(Table)
if(condition) {
builder.where(something)
}
Cursor c = builder.query;
但这是不允许的。
我必须根据我保存在首选项中的条件查询我的数据库。我在 thr 文档中到处搜索和搜索,但找不到一个示例。如果是的话,这个功能是否存在于 dbflow 中,如果没有,那么任何其他 orm(如 greenDAO)是否具有此功能
【问题讨论】:
标签:
orm
query-builder
dbflow
【解决方案1】:
您可以在 DBFlow 中创建条件查询。要查询表的列,您必须将_Table 附加到您的类名,然后访问其属性。这些_Table 类是在构建期间生成的。
最简单的查询是这个:
SQLite.select()
.from(YourTable.class)
.where(YourTable_Table.id.eq(someId)
.queryList();
您还可以在查询中使用.and 和.or 添加新条件:
SQLite.select()
.from(YourTable.class)
.where(YourTable_Table.id.eq(someId)
.and(YourTable_Table.name.eq(someName)
.queryList();
为了更简洁的代码,您还可以将条件分组为条件组,如下所示:
ConditionGroup conditionGroup = ConditionGroup.clause();
conditionGroup.and(YourTable_Table.id.eq(someId);
if (someCondition) {
conditionGroup.and(YourTable_Table.name.eq(someName);
}
return SQLite.select()
.from(YourTable.class)
.where(conditionGroup)
.queryList();
【解决方案2】:
找到了解决我的问题的两种方法
1.来自@trevjonez(特雷弗·琼斯)
Where<SomeModel> query = SQLite.select()
.from(SomeModel.class)
.where(SomeModel_Table.date_field.greaterThan(someValue));
if(someCondition) {
query = query.and(SomeModel_Table.other_field.eq(someOtherValue));
} else {
query = query.and(SomeModel_Table.another_field.isNotNull());
}
Cursor cursor = query.query();
//do stuff with cursor and close it
—
2.from @zshock 使用 ConditionalGroup
ConditionGroup conditionGroup = ConditionGroup.clause();
conditionGroup.and(YourTable_Table.id.eq(someId);
if (someCondition) {
conditionGroup.and(YourTable_Table.name.eq(someName);
}
return SQLite.select()
.from(YourTable.class)
.where(conditionGroup)
.queryList();