Return type for Android Room joins

前端 未结 5 1096
谎友^
谎友^ 2020-11-28 23:31

Let\'s say I want to do an INNER JOIN between two entities Foo and Bar:

@Query(\"SELECT * FROM Foo INNER JOIN Bar ON F         


        
5条回答
  •  北海茫月
    2020-11-29 00:26

    This is my Food Table

    @Entity(tableName = "_food_table")
    data class Food(@PrimaryKey(autoGenerate = false)
                @ColumnInfo(name = "_food_id")
                var id: Int = 0,
                @ColumnInfo(name = "_name")
                var name: String? = "")
    

    This is my Cart table and model class (Food Cart)

    @Entity(tableName = "_client_cart_table")
    data class CartItem(
                    @PrimaryKey(autoGenerate = false)
                    @ColumnInfo(name = "_food_id")
                    var foodId: Int? = 0,
                    @Embedded(prefix = "_food")
                    var food: Food? = null,
                    @ColumnInfo(name = "_branch_id")
                    var branchId: Int = 0)
    

    Note: Here we see _food_id column in two table. It will throw compile time error. From @Embedded doc, you have to use prefix to differentiate between them.

    Inside dao

    @Query("select * from _client_cart_table inner join _food_table on _client_cart_table._food_id = _food_table._food_id where _client_cart_table._branch_id = :branchId")
    fun getCarts(branchId: Int) : LiveData>
    

    This query will return data like this

    CartItem(foodId=5, food=Food(id=5, name=Black Coffee), branchId=1)
    

    I have done this in my project. So Give it a try. Happy coding

提交回复
热议问题