Android Room-查询中使用外键 [英] Android Room - Usage of foreign key in query
问题描述
我有一个Component
,其中包含来自Component_category
I have a Component
which contains a foreign key coming from Component_category
我的目的是按照所选的组件类别过滤组件列表.
My purpose is that a component list will be filtered by the selected component category.
两个类如下:
@Entity(tableName = "component_table", foreignKeys = {
@ForeignKey(
entity = Rack.class,
parentColumns = "rack_id",
childColumns = "component_id",
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
),
@ForeignKey(
entity = ComponentCat.class,
parentColumns = "component_cat_id",
childColumns = "component_id",
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
})
public class Component {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "component_id")
public int componentID;
@NonNull
@ColumnInfo(name = "component_name")
private String componentName;
// .. omitted
组件类别
@Entity(tableName = "component_cat_table")
public class ComponentCat
{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "component_cat_id")
public int componentCatID;
@NonNull
@ColumnInfo(name = "component_cat_name")
private String componentCatName;
// .. omitted
查询
我希望查询如下:
Query
I want my query to be as followed:
@Query("SELECT * from component_table " +
"INNER JOIN component_cat_table " +
"WHERE component_table.component_cat_id == :categoryID ORDER BY component_name ASC")
LiveData<List<Component>> getFilteredComponents(int categoryID);
但是在编译时它告诉我它无法解析component_table.component_cat_id
.我也无法在Component
类的外键实体中设置名称.我尝试了一些选项,但在不访问"外键的情况下不知道如何解决查询.
But at compile time it tells me it can not resolve component_table.component_cat_id
. I am also unable to set a name at the foreign key entity in my Component
class. I tried a few options but I don't know how to fix the query without 'access' to the foreign key.
推荐答案
我偶然发现答案隐藏在名为"android persistence"的示例项目中.
I happened to have found the answer hidden in a sample project called "android persistence".
要使用外键,还必须定义指定外键的列.列与外键数组之间的链接"将自动建立.
In order to use the foreign key, one must define the column of the specified foreign key as well. The 'link' between the columns and the array of foreign keys will automatically be made.
@Entity(foreignKeys = {
@ForeignKey(entity = Book.class,
parentColumns = "id",
childColumns = "book_id"),
@ForeignKey(entity = User.class,
parentColumns = "id",
childColumns = "user_id")})
@TypeConverters(DateConverter.class)
public class Loan {
@PrimaryKey
@NonNull
public String id;
public Date startTime;
public Date endTime;
@ColumnInfo(name="book_id")
public String bookId;
@ColumnInfo(name="user_id")
public String userId;
}
以上示例来自以下链接.
The above sample comes from the following link.
这篇关于Android Room-查询中使用外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!