房间数据库中的ForeignKey

时间:2018-09-27 12:30:25

标签: android database android-room

我正在研究一种结构,其中有几篇文章,其内容存储在两个不同的表中

首先是“文章”表,其中包含以下基本信息:

@Entity(tableName = "Articles")
public class ArticleModel implements Serializable {

    @SerializedName("iArticleID")
    @PrimaryKey(autoGenerate = true)
    public int articleId;

    @ColumnInfo(name = "disciplineId")
    public long disciplineID;

    @SerializedName("tTitle")
    @ColumnInfo(name = "tTitle")
    public String title;

    @SerializedName("file_path")
    @ColumnInfo(name = "article_path")
    public String articlePath;

    @ColumnInfo(name = "lastUpdated")
    public String lastUpdated;

    @ColumnInfo(name = "articleDescription")
    public String articleDescription;

    @ColumnInfo(name = "is_favorite")
    public String isFav = "false";

}

第二个表是FileData,它保存该文章的内容(文件数据),如下所示

@Entity(foreignKeys = @ForeignKey(entity = FileData.class,
        parentColumns = "article_id",
        childColumns = "iArticleID",
        onDelete = CASCADE))
public class FileData implements Serializable {

    @PrimaryKey(autoGenerate = true)
    private int fileId;

    @ColumnInfo(name = "file_name")
    private String fileName;

    @ColumnInfo(name = "file_path")
    private String filePath;

    @ColumnInfo(name = "content")
    private String content;

    @ColumnInfo(name = "article_id")
    public int aId;

}

我想执行一个内部联接查询,该查询也向我提供FilesData以及一些Articles中的列(例如:is_favorite) 为此,我尝试使用FilesData表中提到的F​​oreignKey约束将两个表与article_id相关联。

这是第三个@Embedded类

public class FilesWithArticlesData {

    @Embedded
    ArticleModel articleModel;

    @Embedded
    public FilesData files;

}

,内部联接查询如下:

 @Query("SELECT FilesData.fileId, FilesData.file_name, FilesData.file_path, FilesData.content,articles.is_favorite FROM files" +
            " INNER JOIN ARTICLES ON articles.articleId = FilesData.article_id  " +
            "WHERE FilesData.content LIKE :searchText")
    public LiveData<List<FilesWithArticlesData>> searchContent(String searchText);

每当我尝试运行该应用程序时,都会出现错误

error: (iArticleID) referenced in the foreign key does not exists in the Entity. Available column names:fileId, file_name, file_path, content, article_id

FOREIGN KEY约束失败

任何建议.. ??

1 个答案:

答案 0 :(得分:0)

您输入了错误的parentColumn

只需更改

cls

代替

@Entity(foreignKeys = @ForeignKey(entity = ArticleModel.class,
        parentColumns = "iArticleID",
        childColumns = "article_id",
        onDelete = CASCADE))

还要更改

@Entity(foreignKeys = @ForeignKey(entity = FileData.class,
        parentColumns = "article_id",
        childColumns = "iArticleID",
        onDelete = CASCADE))

对此

 @SerializedName("iArticleID")
    @PrimaryKey(autoGenerate = true)
    public int articleId;