[英]How to create a table with a two or more foreign keys using Android Room?
According theentity-relationship model , the relationship between tbl_post
and tbl_category
could be specified using Room Persistency Library as follows:根据实体关系模型,可以使用Room Persistency Library指定
tbl_post
和tbl_category
之间的关系,如下所示:
@Entity(foreignKeys = @ForeignKey(
entity = TblPost.class,
parentColumns = "id",
childColumns = "tbl_post_id")
)
class TblPostCategory {
@PrimaryKey
public String id;
@ColumnInfo(name = "user_id")
public String postId;
}
However TblPostCategory
depends on two foreign keys: post_id
and category_id
from TblPost
and TbCategory
.然而
TblPostCategory
取决于两个外键:来自TblPost
和TbCategory
post_id
和category_id
。
How the relationship should be described using Room annotations?应该如何使用 Room 注释来描述这种关系?
TblCategory.java TblCategory.java
@Entity
class TblCategory {
@PrimaryKey
@ColumnInfo(name="cat_id")
public String id;
@ColumnInfo(name = "cat_name")
public String name;
}
TblPost.java (It is missing the foreign key reference but it is not important for the case) TblPost.java (它缺少外键引用,但对于这种情况并不重要)
@Entity
class TblPost {
@PrimaryKey
@ColumnInfo(name="post_id")
public String id;
public String title, content, create_time, author_id;
}
TblPostCategory.java TblPostCategory.java
@Entity(foreignKeys = {
@ForeignKey(
entity = TblPost.class,
parentColumns = "post_id",
childColumns = "tbl_post_id"
),
@ForeignKey(
entity = TblCategory.class,
parentColumns = "cat_id",
childColumns = "tbl_category_id"
)
})
class TblPostCategory {
@PrimaryKey
@ColumnInfo(name="tbl_post_id")
public String id;
@ColumnInfo(name = "tbl_category_id")
public String categoryId;
}
In Kotlin:在科特林:
@Entity(
tableName = "some_table",
indices = [Index("id"), Index("brand_id"), Index("model_id")],
foreignKeys = [
ForeignKey(entity = BrandEntity::class, parentColumns = ["id"],
childColumns = ["brand_id"]),
ForeignKey(entity = ModelEntity::class, parentColumns = ["id"],
childColumns = ["model_id"]),
ForeignKey(entity = Table1Entity::class, parentColumns = ["id"],
childColumns = ["table1_id"]),
ForeignKey(entity = Table2Entity::class, parentColumns = ["id"],
childColumns = ["table2_id"])
]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.