This is not enough for recipes. A recipe contains many ingredients, an ingredient belongs to many recipes. So it should be handled with many-to-many relationship.
@Entity
data class Recipe(
@PrimaryKey
val recipeId: Long,
val name: String
)
@Entity
data class KeyIngredient(
@PrimaryKey
val keyIngredientId: Long,
val title: String,
val image: String,
val undertitle: Int,
)
@Entity
data class Step(
@PrimaryKey
val stepId: Long,
val instruction: String,
val stepRecipeId: Long
)
@Entity(
primaryKeys = ["recipeId", "keyIngredientId"]
)
data class RecipeKeyIngredient(
val recipeId: Long,
val keyIngredientId: Long
)
Get the list of ingredients of a recipe
data class RecipeWithIngredients (
@Embedded
val recipe: Recipe,
@Relation(
parentColumn = "recipeId",
entity = KeyIngredient::class,
entityColumn = "ingredientId",
associateBy = Junction(
value = RecipeKeyIngredient::class,
parentColumn = "recipeId",
entityColumn = "keyIngredientId"
)
)
val keyIngredients: List<KeyIngredient>
)
Get the list of recipes with the same ingredient
data class IngredientWithRecipes(
@Embedded
val ingredient: Ingredient,
@Relation(
parentColumn = "ingredientId",
entity = Recipe::class,
entityColumn = "recipeId",
associateBy = Junction(
value = RecipeKeyIngredient::class,
parentColumn = "ingredientId",
entityColumn = "recipeId"
)
)
val recipes: List<Recipe>
)
Now you can query database for the result as:
@Dao
interface RecipeKeyIngredientDao {
@Query("SELECT * FROM Recipe")
fun getRecipeWithIngredients(): LiveData<List<RecipeWithIngredients>>
@Query("SELECT * FROM KeyIngredient")
fun getIngredientWithRecipes(): LiveData<List<IngredientWithRecipes>>
}
For the other part of the question, a recipe typically contains specific set of steps (instructions?) and to define the relationship between recipe and steps you will need nested relationship which defines one-to-many relationship between recipe and steps, and get the recipe from already modelled IngredientsOfRecipe instead of Recipe table which will give recipe with ingredients. Model the same as
data class RecipeWithIngredientsAndSteps(
@Embedded val recipe: IngredientsOfRecipe
@Relation(
entity = Step::class,
parentColumn = "recipeId",
entityColumn = "stepRecipeId"
)
val steps: List<Step>
)
Query using single transaction as follows
@Transaction
@Query("SELECT * FROM Recipe")
fun getRecipeWithIngredientsAndSteps(): List<RecipeWithIngredientsAndSteps>
Please refer to this