Shukri Ibrahimi
Shukri Ibrahimi

Reputation: 79

Merging two entities when querying in Room Database android

Let's say we have User and Order entity

@Entity
public class User{
   int id;
   String name;
}
@Entity
public class Order{
   int id;
   int userId;
   String meal;
}

So when i query

@Query("SELECT * FROM users")
public List<User> loadUsers(); 

I want this output:

{"user":{"id":"","name":"",
"order":{"id":"","userId":"","meal":""}}}

Upvotes: 2

Views: 453

Answers (1)

Szil&#225;rd Gerlei
Szil&#225;rd Gerlei

Reputation: 247

You can use Relation annotation for this problem. Note, the official documentation says [official reference]:

The type of the field annotated with Relation must be a List or Set.

@Entity
public class User{
   @PrimaryKey
   int id;
   String name;
   @Relation(parentColumn = "id", entityColumn = "orderId", entity = Order.class)
   List<Order> orders;
}

@Entity
public class Order{
   @PrimaryKey
   int id;
   int userId;
   String meal;
}

Upvotes: 2

Related Questions