2

我有两个相互关联的模型对象类:

class Car {

    private String model;

    private Manufacturer manufacturer;

    // getter and setter methods

}

和:

class Manufacturer {

    private String name;

    // getter and setter methods

}

如您所见,这些对象是相关的(每辆汽车都有一个制造商)。

现在,在 Realm 中,我需要获取所有汽车,但要按照制造商的名称对其进行排序。如何按关系值排序?

现在,我只有这个:

RealmResults<Car> cars = realm.where(Car.class).findAll();

如何按制造商名称按升序排序?

4

2 回答 2

0

您可能注意到了,但realm.where(Car.class).findAllSorted("manufacturer.name", Sort.ASCENDING)Realm 2.3.x 尚不支持(链接排序)。

在您的情况下,最简单的方法是利用 Realm 作为非 SQL 数据库的优势,并将制造商名称存储在制造商本身旁边。

class Car {

    private String model;

    private Manufacturer manufacturer;

    private String manufacturerName;

    public void setManufacturer(Manufacturer manufacturer) {
        if(manufacturer == null) { 
           this.manufacturerName = null; // direct field access works since 0.88.0
        } else {
           this.manufacturerName = manufacturer.getName();
        }
        this.manufacturer = manufacturer;
    }

}

和:

class Manufacturer {

    private String name;

    // getter and setter methods

}

现在你可以这样做:

RealmResults<Car> cars = realm.where(Car.class)
                              .findAllSorted("manufacturerName", Sort.ASCENDING);
于 2017-02-05T10:54:06.120 回答
-1

你需要像下面这样的东西,

   class MyComp implements Comparator<Manufacturer>
   {

    @Override
    public int compare(Manufacturer o1, Manufacturer o2) {
        // 
    // Compare the o1 properties with o2 properties
   }

}
于 2017-02-05T06:01:31.303 回答