barryalan2633
barryalan2633

Reputation: 840

Many to many android room ref extra variable

I have a Many to Many relationship set up on my Room database denoted by the following diagram:

Relationship diagram

eveything works great but I would like to make the following addition: Updated relationship diagram

My question is how do I go about having RecipeWithIngredients get this unit:String variable from the RecipeIngredientRef Entity when a recipeWithIngredients is constructed on a query?

    @Entity(indices = [Index(value = ["name"],unique = true)])
data class Recipe(
    var name: String,
    val image: String?
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "recipeID")
    var ID: Long = 0
}

@Entity(indices = [Index(value = ["name"],unique = true)])
data class Ingredient(
    val name: String,
    val image: String?,
    val amount: Int
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "ingredientID")
    var ID: Long = 0
}

@Entity(primaryKeys = ["recipeID", "ingredientID"])
data class RecipeIngredientRef(
    val recipeID: Long,
    val ingredientID: Long,
    val unit: String
)

data class RecipeWithIngredients(
    @Embedded
    val recipe: Recipe,
    @Relation(
        parentColumn = "recipeID",
        entity = Ingredient::class,
        entityColumn = "ingredientID",
        associateBy = Junction(
            value = RecipeIngredientRef::class,
            parentColumn = "recipeID",
            entityColumn = "ingredientID"
        )
    )
    val ingredients: List<Ingredient>
)

Upvotes: 0

Views: 306

Answers (1)

sergiy tykhonov
sergiy tykhonov

Reputation: 5103

As far as I know there is no built-in way using current many-to-many Relations in Room for that. So I just want to save your time for researches.

This RecipeIngredientRef table is used internally just for two other tables' join and for now adding there additional fields will not help to get these fields with @Relations/Junction mechanism.

You can try workarounds, but they are no so elegant and they needed to dig deeper into Room's result's processing:

  1. Don't use @Relation/Junction mechanism for RecipeWithIngridients at all, write your own query with two JOINs (since you should get data from 3 tables). As a result you'll get some raw set of records and then you should use loops and methods of Kotlin collections to turn result into needed form.
  2. Use @Relation/Junction mechanism, but after getting result - make additional processing of result - make one more query to RecipeIngredientRef table and set missing unit value manually (again with loops and methods of Kotlin collections).

Upvotes: 1

Related Questions