Katedral Pillon
Katedral Pillon

Reputation: 14864

How to access entities from many to many relationships

Here is the explanation. I have two entities: House, Person. In my system one person may own multiple houses and one house may have multiple owners. So I create a table (aka entity) called HouseOwnership. I want to be able to make two different kinds of queries against HouseOwnership:

So for HouseOwnership, I do

@Entity
class HouseOwnership{
  @Load
  private Ref<House> houseRef;
  @Load
  private Ref<Person> personRef;
}

How do I make my queries with OfyService.ofy()?

I am tempted to do

owners =OfyService.ofy().load().type(HouseOwnership.class).ancestor(house).list()

and

houses =OfyService.ofy().load().type(HouseOwnership.class).ancestor(person).list()

but for this I would have to make both References into @Parent. So am I allowed to do that? How do I make the queries?

Also I only have the ids not the actual objects so I would have to create the objects from the ids, which I can do. But I am wondering if there is an easier way?

Upvotes: 0

Views: 47

Answers (2)

stickfigure
stickfigure

Reputation: 13556

You almost certainly want to model this as a @Index Set<Ref<Person>> owners; property on House. Creating an extra relationship entity creates a significant amount of overhead.

Don't try to map schemas literally from relational models - use the document structure to your advantage.

Upvotes: 0

Andrei Volgin
Andrei Volgin

Reputation: 41099

  1. An entity can have only one parent.

  2. You don't need to make your HouseOwnership entity a child of any entity.

  3. You make a simple query to get all HouseOwnership entities where houseRef property equals a given House key, or personRef property equals a given Person key, or both.

  4. You can always make a Key from an ID for entities that have no parents.

Upvotes: 1

Related Questions