Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

greendao sort by field in related table

is there a way to sort by a field in a related table with greenDao? E.g. I have a table of cars and a table of drivers. Each car has a driver. Now I want to query for ( e.g. blue ) cars and sort by the name of the driver

like image 832
ligi Avatar asked Apr 16 '13 16:04

ligi


3 Answers

In QueryBuilder, there are methods to specify the sorting order. Look for methods starting with "order...", e.g. orderAsc(Property).

like image 71
Markus Junginger Avatar answered Sep 30 '22 14:09

Markus Junginger


I play around with GreenDao at the moment too and hope my little addition to the comment in the first answer and the description in the queries part of the greenDao documentation helps.

The following snippet should work (didn't test it :)):

Query query = carsDao.queryRawCreate(   ", driver D WHERE T.COLOR='blue' AND T.DRIVER_ID=D._ID ORDER BY D.NAME ASC");

This creates internally a SQL similiar to this:

SELECT T.'id', T.'name', T.'color', T.'driver_id'
FROM cars T, driver D
WHERE T.COLOR='blue'
AND T.DRIVER_ID=D._ID
ORDER BY D.NAME ASC

The first part of the statement is created for you by the queryRawCreate method, the rest is the custom sql statement which was passed to queryRawCreate.

See this question if you wonder where the JOIN statement is.

like image 44
Sven Avatar answered Sep 30 '22 15:09

Sven


You can use QueryBuilders with the (data access objects) DAOs that are generated by the Greendao ORM.

Define before you use (in Activities)

 ProductDao productDao;
 DaoSession daoSession;

You should place the DaoMaster and DaoSession in your application scope. Inside the onCreate() of the class that extends Application.

DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getApplicationContext(), "app-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
daoSession = new DaoMaster(db).newSession();

Initialize before you use

 daoSession = ((MyApplication) getApplication()).getDaoSession();
 productDao = daoSession.getProductDao();

You can sort the results like this to display in the activity.

private void refreshProducts() {
        switch (sorted_by){
            case SORT_BY_DATE:
                cardItems = productDao.queryBuilder().orderAsc(ProductDao.Properties.Id).list();
                setupRecyclerView();
                break;

            case SORT_BY_PRICE:
                cardItems = productDao.queryBuilder().orderDesc(ProductDao.Properties.Price).list();
                setupRecyclerView();
                break;

            case SORT_BY_POPULARITY:
                cardItems = productDao.queryBuilder().orderDesc(ProductDao.Properties.Name).list();
                setupRecyclerView();
                break;
        }
    }
like image 20
Vishal Kumar Avatar answered Sep 30 '22 15:09

Vishal Kumar