Search code examples
ormquery-builderdbflow

Query builder dbflow conditional query


how can i build a query based on certain conditions .

i tried doing this

QueryBuilder builder = SQlite.Select().from(Table)
    if(condition) {
         builder.where(something)
    }
Cursor c = builder.query;

but it is not permitted.

I have to query my database on conditions that i have saved in preferences . I googled and searched everywhere in thr docs but couldn't find a single example . do this feature exists in dbflow if yes then how if no is thr any other orm (like greenDAO) with this feature


Solution

  • You can create conditional queries in DBFlow. To query a table's columns you must append _Table to your class name, then access its property. These _Table classes are generated during build time.

    The most simple query would be this one:

    SQLite.select()
          .from(YourTable.class)
          .where(YourTable_Table.id.eq(someId)
          .queryList();
    

    You can also add new conditions by using .and and .or in your query:

    SQLite.select()
          .from(YourTable.class)
          .where(YourTable_Table.id.eq(someId)
          .and(YourTable_Table.name.eq(someName)
          .queryList();
    

    For a cleaner code, you can also group conditions into condition groups like this:

    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();