1

I have LoggedInUserEntity and UserRecentSearch where the last one has foreignKeys to LoggedInUserEntity. When I want to delete LoggedInUserEntity it is possible if only no UserRecentSearch are in database.

How do i delete?

@Query("DELETE FROM loggedInUser")

How do i use relationships?

@Entity(tableName = "recentSearches",
    indices = arrayOf(Index(value = "userId",name = "idr")),
    foreignKeys = arrayOf(ForeignKey(
            entity = LoggedInUserEntity::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("userId"))
    ))

How can i delete LoggedInUserEntity with existing UserRecentSearch?

1 Answers1

0

You need to add the cascade property to your foreign key constraint for the onDelete method which would look something like this:

@Entity(tableName = "recentSearches",
    indices = arrayOf(Index(value = "userId", name = "idr")),
    foreignKeys = arrayOf(ForeignKey(
    entity = LoggedInUserEntity::class
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("userId"),
        onDelete = CASCADE
    ))
))

This means that when you delete the LoggedInUser from your DB any of the recentSearches for that user with the foriegn key will also be deleted.

James Lendrem
  • 1,780
  • 2
  • 15
  • 23
  • I have left default NO_ACTION because RecentSearches must not be deleted. As far as i understand, my case might be solved only with UPDATE entity but not with DELETE – Roma Heshten Mar 21 '18 at 13:49
  • If you delete a loggedInUser and have a recent search with a foreign key that references it your database will become inconsistent and that's why it won't allow you to delete the loggedInUser due to that inconsistency. If you are wanting to keep recent searches I'd create another table along the lines of: User, LoggedInUser, and RecentSearches. You then have your recent searches reference the User table and have logged in user also reference the user table. That way when you delete the LoggedInUser the constraints will still be valid. – James Lendrem Mar 22 '18 at 11:19