简体   繁体   中英

Listing All data Based on foreign keys android room

I've googled my question and i can't find the answer yet.

I want to get all the meals that is in favorite, below is the code and what i have tried.
The result is that i only get a single Meal, even though there are 3 data in dbfavoritemeal.
The expected result is that i will get all the meals based on all the mealid in dbfavoritemeal.
Please guide me

I have a meal class

@Entity
data class DbMeal(
    @PrimaryKey val id: Long,
    val name: String,
    val thumbnailUrl: String,
    val category: String,
    val instructions: String = "",
) {

And then i have favorite class

@Entity(
    foreignKeys = [
        ForeignKey(
            entity = DbMeal::class,
            parentColumns = ["id"],
            childColumns = ["mealId"],
            onDelete = ForeignKey.CASCADE
        )],
    indices = [Index(
        value = ["mealId"],
        unique = true
    )]
)
data class DbFavoriteMeal(
    @PrimaryKey
    val mealId: Long
)

What i've tried is in DAO

@Query("select * from dbMeal where id = (select mealId from dbfavoritemeal)")
suspend fun getAllFavoriteDbMeal(): List<DbMeal>

You can change your DAO like

@Query("select * from dbMeal where id in (select mealId from dbfavoritemeal)")
suspend fun getAllFavoriteDbMeal(): List<DbMeal>

or you can add isFavorite parameter to your Entity.

@Entity
data class DbMeal(
    @PrimaryKey val id: Long,
    val name: String,
    val thumbnailUrl: String,
    val category: String,
    val instructions: String = "",
    val isFavorite: Boolean = false,
)

And your DAO should look like

@Query("select * from dbMeal where isFavorite = 1")
suspend fun getAllFavoriteDbMeal(): List<DbMeal>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM