Java android房间两个外键

时间:2018-12-12 10:08:33

标签: java android android-room

我有一个带有两个外键的表到两个不同的表中

这是我的桌子:

@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;

当我将图片插入数据库时​​,我得到:

  

android.database.sqlite.SQLiteConstraintException:FOREIGN KEY约束失败(代码787)

3 个答案:

答案 0 :(得分:1)

我认为您必须更改此行

> db.mylocations.find().pretty()
{
    "_id" : ObjectId("5c10de4fb5f14ec21b3fa24b"),
    "extent" : {
        "coOrdinates" : [
            [
                [
                    1,
                    2
                ],
                [
                    1,
                    2
                ],
                [
                    1,
                    2
                ],
                [
                    1,
                    2
                ],
                [
                    1,
                    2
                ]
            ]
        ],
        "type" : "poly"
    },
    "__v" : 0
}

答案 1 :(得分:0)

似乎您没有添加任何两个行的父表,例如BIN.class和Order.class。我从Here

得到了答案

答案 2 :(得分:0)

尝试这样做

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"
            )]),

可能有帮助