Android的DBFlow没有好文档,在阅读了有关如何在两个表之间建立简单关系的更多信息后,我无法做到这一点。
我有两张桌子:
MainCategories
和SubCategories
在SubCategories
我channelId
存储MainCategories
,MainCategories
SubCategories
表上有更多数据,(一对多)
现在我正试图实现这种关系:
我的代码不正确,与库文档
相似 MainCategories
:
@Table(database = AppDatabase.class)
public class ChannelContentCategories extends BaseModel {
@PrimaryKey(autoincrement = true)
private int id;
@Column
private int channelId;
@Column
private String title;
List<ChannelSubContentCategories> subContentCategories;
@OneToMany(methods = {OneToMany.Method.ALL})
public List<ChannelSubContentCategories> getMyChannelSubContentCategoriess() {
...
}
...
}
SubCategories
:
@Table(database = AppDatabase.class)
public class ChannelSubContentCategories extends BaseModel {
@PrimaryKey(autoincrement = true)
private int id;
@Column
private int categoryId;
@Column
private int parentId;
@Column
private String title;
...
}
如何在channelId
表格ChannelContentCategories
与parentId
表格ChannelSubContentCategories
之间建立简单关系?
提前致谢
答案 0 :(得分:1)
此处的问题是DBFlow仅支持ForeignKey
引用另一个表的PrimaryKey
列。因此,您有3种不同的方式来实现您的关系:
@PrimaryKey
移至ChannelContentCategories
从id
移至channelId
parentId
引用id
代替channelId
,因此channelId
不需要PrimaryKey
id
主键定义为autoincremented
所以,我最终得到了第三种方式,看看我们拥有的东西:
<强> ChannelContentCategories.java 强>
@Table(database = AppDatabase.class)
public class ChannelContentCategories extends BaseModel {
@PrimaryKey
@Column
public int id;
@PrimaryKey
@Column
public int channelId;
@Column
public String title;
public List<ChannelSubContentCategories> subContentCategories;
@OneToMany(methods = {OneToMany.Method.ALL}, variableName = "subContentCategories") // this should be equal to the field name, that contains children
public List<ChannelSubContentCategories> getMyChannelSubContentCategories() {
if (subContentCategories == null || subContentCategories.isEmpty()) {
subContentCategories = SQLite.select()
.from(ChannelSubContentCategories.class)
.where(ChannelSubContentCategories_Table.parentId.eq(channelId))
.queryList();
}
return subContentCategories;
}
...
}
<强> ChannelSubContentCategories.java 强>
@Table(database = AppDatabase.class)
public class ChannelSubContentCategories extends BaseModel {
@PrimaryKey(autoincrement = true)
@Column
public int id;
@Column
public int categoryId;
@Column
@ForeignKey(tableClass = ChannelContentCategories.class,
references = @ForeignKeyReference(columnName = "parentId", foreignKeyColumnName = "channelId"))
public int parentId;
@Column
public String title;
...
}
我测试了它并且它有效。随意选择最合适的方式。
答案 1 :(得分:0)
您是否希望将channelId用作MainCategories的外键?
像这样? :@ForeignKey(tableClass = SubCategories.class)
@Column
private int channelId;
答案 2 :(得分:-1)
您不必从数据库加载数据,然后将其关联起来。只需使用SQL语句来组合所有这些信息。
SELECT column_name.Table_name1, column_name.Table_name2, column_name.Table_name3 FROM Table_name1, Table_name2, Table_name3 WHERE id.Table_name1 == id.Table_name2 && id.Table_name1 == id.Table_name3;
希望它会有所帮助