greendao按相关表格中的字段排序

时间:2013-04-16 16:43:46

标签: android greendao

有没有办法用greenDao按相关表格中的字段排序?例如。我有一张汽车桌和一张司机桌。每辆车都有一个司机。现在我想查询(例如蓝色)汽车并按驱动程序名称排序

4 个答案:

答案 0 :(得分:5)

此刻我也和GreenDao一起玩,希望我对第一个答案中的评论和queries part of the greenDao documentation中的说明有所帮助。

以下代码段应该有效(不测试它:)):

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

这在内部创建了一个与此类似的SQL:

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

该语句的第一部分是由queryRawCreate方法为您创建的,其余部分是传递给queryRawCreate的自定义sql语句。

如果你想知道JOIN语句在哪里,请参见this question

答案 1 :(得分:4)

在QueryBuilder中,有一些方法可以指定排序顺序。寻找以“order ...”开头的方法,例如orderAsc(属性)。

答案 2 :(得分:1)

您可以将QueryBuilders与由greendao ORM生成的Dao一起使用。

使用前定义

 ProductDao productDao;
 DaoSession daoSession;

您应该将DaoMaster和DaoSession放在您的应用范围内。在扩展Application的类的onCreate()内部。

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

使用前初始化

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

您可以对结果进行排序,以便在活动中显示。

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;
        }
    }

答案 3 :(得分:0)

使用QueryBuilder.orderRaw()和Join.getTablePrefix()的简便解决方案

我的示例代码:

QueryBuilder.LOG_SQL = true;//Enable to see SQL result

  QueryBuilder<Item> query = daoSession.queryBuilder(Item.class);
  Join itemWithCollection = query.join(JoinItemWithCollection.class,
      JoinItemWithCollectionDao.Properties.ItemId);
  String joinedTable = itemWithCollection.getTablePrefix();
  Join collection = query.join(itemWithCollection, JoinItemWithCollectionDao.Properties.CollectionId,
      Collection.class, CollectionDao.Properties.Id);
  String orderCol = JoinItemWithCollectionDao.Properties.SomeOrderCol.columnName;
  collection.where(CollectionDao.Properties.Key.eq(collectionId));
  query.orderRaw(joinedTable+".\""+orderCol+"\" DESC");
  query.limit(limit);
  query.offset(from);

  List<Item> results = query.list();
相关问题