简体   繁体   中英

Java android room two foreign key

I have a table with two foreign key into two different tables

This is my table:

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

and when I insert a PICTURE to the database I get:

android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787)

i think you must change this lines

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

It seems you did not add any row two parent table like BIN.class and Order.class. I got an answer from Here

Try to do it like this

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

Actually in kotlin I wrote this line in the following way

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

May be it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM