我有两个彼此相关的模型对象类:
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();
如何按制造商的名称按升序对其进行排序?
答案 0 :(得分:0)
您可能已注意到,但Realm 2.3.x尚不支持realm.where(Car.class).findAllSorted("manufacturer.name", Sort.ASCENDING)
(链接排序)。
在您的情况下,最简单的方法是利用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);
答案 1 :(得分:-1)
您需要如下所示的内容,
class MyComp implements Comparator<Manufacturer>
{
@Override
public int compare(Manufacturer o1, Manufacturer o2) {
//
// Compare the o1 properties with o2 properties
}
}