Azartys
Azartys

Reputation: 543

Android Room One to many relation query reverse

I have a One to Many relation between two objects. I have, lets say, a user that have many pets.

Using this I can retrieve my object

data class UserWithPets (
        @Embedded
        var user: User? = null,

        @Relation(parentColumn = "id", entityColumn = "user_id", entity = Pet::class)
        var pets: List<Pet>? = null
)

UserDao:

@Transaction @Query("SELECT * FROM users")
fun getUserWithPets() : LiveData<List<UserWithPets>>

This is working correctly. Now I want to get the list of Pet with each User associated... Something that would be PetWithUser.

So I did:

data class PetWithUser (
        @Embedded
        var pet: Pet? = null,

        @Relation(parentColumn = "user_id", entityColumn = "id", entity = Pet::class)
        var user: User? = null
)

PetDao:

@Transaction @Query("SELECT * FROM pets")
fun getPetsWithUser(): LiveData<List<PetWithUser>>

As soon as I add the getPetsWithUser to the code I get errors with the DataBinding class generation.

How can I do a One to Many relation and get the pet with the user ?

edit:

Error log: They are from the DataBinding java files generated. The second one (HomeFragmentDataBinding) does not use the PetWithUser but raise error when PetWithUser is added to the code...

error: cannot find symbol
  protected ListItemBinding(DataBindingComponent _bindingComponent, View _root,
                                   ^
  symbol:   class DataBindingComponent
  location: class ListItemBinding

error: cannot find symbol
      @Nullable ViewGroup root, boolean attachToRoot, @Nullable DataBindingComponent component) {
                                                                ^
  symbol:   class DataBindingComponent
  location: class FragmentHomeBinding

Upvotes: 10

Views: 1000

Answers (2)

Hammer
Hammer

Reputation: 1048

Correct version would be:

data class PetWithUser (
    @Embedded
    var pet: Pet,

    @Relation(parentColumn = "owner_id", entityColumn = "user_id")
    var user: User? = null
)

where

  • owner_id is id of User defined in Pet class
  • user_id is matching user id defined in User class

Upvotes: 1

Reagankm
Reagankm

Reputation: 5419

You've probably long since figured this out, but it looks like your only problem was that you put down Pet class on your Relation line instead of User class:

@Relation(parentColumn = "user_id", entityColumn = "id", entity = Pet::class)
        var user: User? = null

instead of

@Relation(parentColumn = "user_id", entityColumn = "id", entity = User::class)
        var user: User? = null

Upvotes: 0

Related Questions