I am working on a nutrition tracking app. For that I am trying to setup a many to many relation with some additional fields using Room library. I am not sure yet if its even possible?
The use case I am having trouble with is that I want to retrieve a list of Meals(Breakfast, Lunch, Dinner) along with the foods the user has had along with the portion sizes. So it will be something like -> Meals would have a List of Item. Item would have (1)Food + (2)portionSize of that food. The classes are as follows:
@Entity
public class Meal {
@PrimaryKey( autoGenerate = true)
@ColumnInfo(name = "MEAL_ID")
private Long mealId;
}
@Entity
public class Food {
@PrimaryKey( autoGenerate = true)
@ColumnInfo(name = "FOOD_ID")
private Long id;
}
//Join Table
@Entity(tableName = "MEAL_FOOD", primaryKeys = {"MEAL_ID", "FOOD_ID"})
public class MealFood {
@ColumnInfo(name = "MEAL_ID")
private Long mealId;
@ColumnInfo(name = "FOOD_ID")
private Long foodId;
private Double portionSize;
}
Now for accessing the data, I am trying something like the following pojo:
public class MealWithFoods {
@Embedded
public Meal meal;
@Relation(parentColumn = "MEAL_ID", entityColumn = "FOOD_ID", entity = Food.class, associateBy = @Junction(MealFood.class))
public List<Item> items;
}
public class Item {
@Embedded
private Food food;
@Relation(parentColumn = "FOOD_ID", entityColumn = "FOOD_ID", projection = {"PORTION_SIZE"}, entity = MealFood.class)
private Double portionSize;
}
DAO:
public interface MealsWithFoodsDao {
@Transaction
@Query("SELECT * FROM MEAL")
public List<MealWithFoods> getMealsWithFoods();
}
I have been trying at it for sometime now. Can someone pls offer a path forward. Thanks.