簡體   English   中英

java android room 兩個外鍵

[英]Java android room two foreign key

我有一個表有兩個外鍵到兩個不同的表

這是我的桌子:

@Entity(
        tableName = Constants.TABLE_NAME_PICTURE,
        foreignKeys = {
        @ForeignKey(
                entity = BIN.class,
                parentColumns = "id",
                childColumns = "bin_id"
        ),
        @ForeignKey(
                entity = ORDER.class,
                parentColumns = "id",
                childColumns = "order_id"
        )},
        indices = {@Index("id"), @Index(value = {"bin_id","order_id"})})

public class PICTURE {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    public long id;
    @Attribute(name = "name", required = false)
    @ColumnInfo(name = "name")
    public String name;
    @ColumnInfo(name = "bin_id")
    public int binId;
    @ColumnInfo(name = "order_id")
    public int orderId;

當我將 PICTURE 插入數據庫時,我得到:

android.database.sqlite.SQLiteConstraintException:外鍵約束失敗(代碼 787)

我認為你必須改變這一行

foreignKeys = {
    @ForeignKey(
            entity = BIN.class,
            parentColumns = {"id"},
            childColumns = {"bin_id"}
    ),
    @ForeignKey(
            entity = ORDER.class,
            parentColumns = {"id"}
            childColumns = {"order_id"}
    )},

看起來你沒有添加任何行兩個父表,如 BIN.class 和 Order.class。 我從這里得到了答案

嘗試這樣做

foreignKeys = [
        @ForeignKey(
                entity = BIN.class,
                parentColumns = "id",
                childColumns = "bin_id"
        ),
        @ForeignKey(
                entity = ORDER.class,
                parentColumns = "id",
                childColumns = "order_id"
        )],

實際上在科特林我用下面的方式寫了這一行

foreignKeys = arrayOf(
            @ForeignKey(
                    entity = BIN.class,
                    parentColumns = "id",
                    childColumns = "bin_id"
            ),
            @ForeignKey(
                    entity = ORDER.class,
                    parentColumns = "id",
                    childColumns = "order_id"
            )]),

可能有幫助

暫無
暫無

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

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