Lena
Lena

Reputation: 561

Room How to fetch on 3 tables with Foreign Keys

I have a table named User. This table has two foreign keys Account and Shop (both 1..1 relationship). So I've created a data class called UserAndAccount and another called UserAndShop.

How can I now fetch all this data (would be equal to UserAndAccountAndShop) ?

User.kt

@Entity(
    tableName = "User"
)
data class User(

    @PrimaryKey(autoGenerate = false)
    @SerializedName("unique_id")
    var uniqueID: String,

    @SerializedName("email")
    var email: String = "",

    @SerializedName("username")
    var username: String = ""
)

Account.kt

@Entity(
    tableName = "Account"
)
data class Account(

    @PrimaryKey(autoGenerate = true)
    @SerializedName("account_id")
    var accountID: Int,

    @SerializedName("user_id")
    var userOwnerID: String = "",

    @SerializedName("token")
    var token: String = ""
)

Shop.kt

@Entity(
    tableName = "Shop"
)
data class Shop(

    @PrimaryKey(autoGenerate = true)
    @SerializedName("shop_id")
    var shopID: Int,

    @SerializedName("shop_owner_id")
    var shopOwnerID: String,

    @SerializedName("shop_name")
    var shopName: String = ""
)

UserAndAccount.kt

data class UserAndAccount(
    @Embedded val user: User,
    @Relation(
        parentColumn = "uniqueID",
        entityColumn = "userOwnerID"
    )
    val account: Account
)

UserAndShop.kt

data class UserAndShop(
    @Embedded val user: User,
    @Relation(
        parentColumn = "uniqueID",
        entityColumn = "shopOwnerID"
    )
    val shop: Shop
)

Upvotes: 1

Views: 120

Answers (1)

Lena
Lena

Reputation: 561

To anyone looking for an answer:

You can add multiples @Relation into a data class. So I've created this data class:

UserAndAccountAndShop.kt

data class UserAndAccountAndShop(
    @Embedded val user: User,
    @Relation(
        parentColumn = "uniqueID",
        entityColumn = "accountOwnerID"
    )
    val account: Account,

    @Relation(
        parentColumn = "uniqueID",
        entityColumn = "shopOwnerID"
    )
    val shop: Shop
)

And that's it!

Upvotes: 1

Related Questions