【问题标题】:Inserting data into foreign key table in SQLite android在SQLite android中将数据插入外键表
【发布时间】:2019-10-01 10:56:26
【问题描述】:

我必须在数据库中插入一个帖子,它是多个图像,所以我创建了以下表格

张贴表:

@Entity
data class PostTable(
  var post: String,
  var images : ArrayList<String>) : Parcelable{

    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}

图像表:

@Entity(foreignKeys = arrayOf(ForeignKey(entity = PostTable::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("imd"),
        onDelete = ForeignKey.CASCADE)))
data class ImageTable (
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val imd: Int,
    val imageURL: String
)

道帖表:

@Dao
interface PostDao {
    @get:Query("SELECT * FROM PostTable ORDER BY id ASC")
    val posts: LiveData<MutableList<PostTable>>

    @Insert
    fun insert(post: PostTable)
}

道影像表

@Dao
interface ImageDao {
    @Insert
    fun insert(images: ImageTable)

    @Query("SELECT * FROM ImageTable WHERE imd=:postID")
    fun allImages(postID: Int): List<ImageTable>
}

我可以在 PostTable 中插入值,如何通过获取 PostTable 的 id 来将值插入到 PostTable 和它的图像到 ImageTable 中?

【问题讨论】:

    标签: android sqlite android-sqlite android-room


    【解决方案1】:

    您不需要在数据库级别存储帖子拥有的图像,因为每个图像都将存储一个指向其拥有(父)帖子的链接。

    因此,您希望对var images : ArrayList&lt;String&gt;) : Parcelable{ 使用@Ignore 注释(@Ignore 排除它作为表中的一列)。

    你想要的是一个提取图像路径的函数。这将像在 ImageDao 中一样使用 allImages 查询,因此您应该将 ImageDao 对象传递给函数。

    因此,您的代码可能包含以下内容:-

    @Ignore
    internal var images = ArrayList<String>()
    
    constructor() {}
    
    fun getImages(imageDao: ImageDao): ArrayList<String> {
        val result = ArrayList<String>()
        val imageTableList = imageDao.allImages(this.id!!)
        for (it in imageTableList) {
            result.add(it.getImageURL())
        }
        return result
    }
    
    fun getImages(): ArrayList<String> {
        return this.images
    }
    
    fun setImages(imageDao: ImageDao) {
        this.images = getImages(imageDao)
    }
    

    然后您可以使用getImages() 检索由setImages(your_ImageDao_instance) 存储的ArrayList(必须运行它以保持图像更新),或者您可以使用getImages(your_ImageDao_instance)(根据数据库获取imageUrl) (即 PostTable 中不需要 images 变量)。

    • 请注意,以上代码为in-principal code,未经测试或运行,因此可能包含一些错误。

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 2011-09-09
      相关资源
      最近更新 更多