Room @Relation 有两个外键

Room @Relation with two foreign keys

我有三个实体:

假设我想像往常一样收到带有所有者和品牌的汽车SELECT我只收到外键的 ID。

我的方法是使用@Relation:

public class CarWithPersonAndBrand {

    @Embedded Person person;
    @Relation(parentColumn =  "id", entityColumn = "brandId",  entity = Brand.class)
    Car brand;
    
    @Relation(parentColumn =  "id", entityColumn = "personId",  entity = Person.class)
    Car car; //this would not make anysence???
}

但是使用关系注释,我收到了注释外键的对象,但是我想要其他方法。而不是接收两个汽车对象,这没有意义我的建议是使用@Relation 注释接收品牌和人物对象,这可能吗?

认为您想要 CarWithPersonAndBrand

所以你想要 Car 与相应的(相关)Person 和相应的 Brand.

所以你从汽车 table 得到汽车,从各自相关的 table 得到相关的人和相关的品牌。

所以你可以使用:-

class CarWithPersonAndBrand {

    @Embedded
    Car  car;
    @Relation(entity = Person.class,parentColumn = "idPerson",entityColumn = "personId")
    Person person;
    @Relation(entity = Brand.class,parentColumn = "idBrand",entityColumn = "brandId")
    Brand brand;
}

这是使用您的图表构建的,显示汽车 table 有列 idPersonidBrand 并且您的 CarWithPersonAndBrand class 表示 Person table 有 personId 列,Brand table 有 brandId 列(每个都唯一标识各自的行)。

使用以下 Dao :-

@Transaction
@Query("SELECT * FROM car")
List<CarWithPersonAndBrand> getAllCarsWithPersonAndBrand();

以及 activity 中的以下内容:-

public class MainActivity extends AppCompatActivity {

    MotorDatabase db;
    AllDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = MotorDatabase.getInstance(this);
        dao = db.getAllDao();

        Person p1 = new Person("Mary");
        Person p2 = new Person("Fred");
        Brand b1 = new Brand("Ford");
        Brand b2 = new Brand("Chevrolet");


        p1.personId = dao.insert(p1);
        p2.personId = dao.insert(p2);
        b1.brandId = dao.insert(b1);
        b2.brandId = dao.insert(b2);

        Car c1 = new Car("MyCar",p1.personId,b1.brandId);
        Car c2 = new Car("TheirCar",p2.personId,b1.brandId);
        dao.insert(c1);
        dao.insert(c2);
        List<CarWithPersonAndBrand> carsList = dao.getAllCarsWithPersonAndBrand();

        for (CarWithPersonAndBrand c: carsList) {
            Log.d("CARINFO","Car is " + c.car.carName + " owner is " + c.person.personName + " brand is " + c.brand.brandName);
        }
    }
}

那么上面的log输出的结果就是:-

D/CARINFO: Car is MyCar owner is Mary brand is Ford
D/CARINFO: Car is TheirCar owner is Fred brand is Ford