簡體   English   中英

Android房間的多對多關系查詢總是只返回一個結果

[英]Many to Many Relationship Query in Android Room always returns only one result

我嘗試查詢某個制造商的數據庫,它返回一組產品。 這個表之間的關系是多對多的,我為這些使用了一個聯結表。 但是,如果我嘗試在 Room 中設置查詢,它總是只返回該制造商的一種產品。 我想要具有給定 ID 的制造商的所有產品。

這是表:

@Entity(tableName = "manufacturer")
public class ManufacturerEntry {
    @PrimaryKey
    private int id;
    private String name;
}

這是表:

@Entity(tableName = "product")
public class ProductEntry {
    @PrimaryKey
    private int id;
    private String shoeType;
    private String name;
}

這是聯結表:

@Entity(tableName = "bom", foreignKeys = {@ForeignKey(entity = ManufacturerEntry.class, parentColumns = "id", childColumns = "manufacturerId"),
        @ForeignKey(entity = ProductEntry.class, parentColumns = "id", childColumns = "productId")}, primaryKeys = {"productId", "manufacturerId"})
public class BomEntry {
    private int productId;
    private int manufacturerId;
}

這是關系 class:

public class ManufacturerWithProducts {
    @Embedded
    public ManufacturerEntry manufacturerEntry;
    @Relation(
            parentColumn = "id",
            entityColumn = "id",
            associateBy = @Junction(value = BomEntry.class, parentColumn="manufacturerId", entityColumn = "productId")
    )
    public List<ProductEntry> productEntryList;
}

最后是DAO接口:

@Transaction
@Query("SELECT * FROM manufacturer WHERE id = :id")
LiveData<List<ManufacturerWithProducts>> loadManufacturerWithProducts(int id);

我最終在 DAO 之上使用了一個常規的 SQL 查詢,並為該查詢構建了一個單獨的返回值 object。

public class ManufacturerAndProductNames {
    public String manufacturerName;
    public String productName;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM