Reputation: 1558
I have to insert a post and it's multiple images into a database, so i created the following tables
Post Table:
@Entity
data class PostTable(
var post: String,
var images : ArrayList<String>) : Parcelable{
@PrimaryKey(autoGenerate = true)
var id: Int = 0
}
Image Table:
@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 Post Table:
@Dao
interface PostDao {
@get:Query("SELECT * FROM PostTable ORDER BY id ASC")
val posts: LiveData<MutableList<PostTable>>
@Insert
fun insert(post: PostTable)
}
Dao Image Table:
@Dao
interface ImageDao {
@Insert
fun insert(images: ImageTable)
@Query("SELECT * FROM ImageTable WHERE imd=:postID")
fun allImages(postID: Int): List<ImageTable>
}
i can insert values into PostTable, how to insert into PostTable and it's images into ImageTable by getting the id of PostTable ?
Upvotes: 1
Views: 58
Reputation: 57073
You don't need to store the images owned by a post at the database level as each image will be stored with a link to it's owning (parent) post.
Therefore you want to use the @Ignore annotation for var images : ArrayList<String>) : Parcelable{
(@Ignore excludes it being a column in the table).
What you want is a function to extract the image paths. This would used the allImages query as in ImageDao, as such you should pass an ImageDao object to the function.
As such your code could include something like :-
@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)
}
You could then use getImages()
to retrieve the ArrayList as stored by setImages(your_ImageDao_instance)
(which would have to be run to keep the images updated) or alternately you could use getImages(your_ImageDao_instance)
(which get's the imageUrl's according to the database (i.e. there would then be no need for the images variable in PostTable)).
Upvotes: 2