Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 463
Azartys Avatar asked Aug 24 '18 14:08

Azartys


1 Answers

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
like image 78
Hammer Avatar answered Nov 07 '22 11:11

Hammer