4

I am wondering if there is a way to directly query objects by relationship object's attribute?

It might sound confusing, for example:

Each user have many installations, I have pointer from each installation to its user, forming a many to one relationship.

I would like to find all installation that belongs to one user with given username.

Similar use case: find all installations that belong to user whose last name is 'James'. But there are many users instead of one in this case.

My current solution is, query.find the user with given criteria, and then for each user do an installation query with query.equalTo("user", fetchedUser). This just feels very cumbersome and expensive.

Another solution is to "flattening" objects and put as many attributes on the querying target object as possible. So we can just use a query.find for one time. For our examples: put copies of username and last name on installation. But then the data is less relational if we end up just not using a user object; if we choose to keep user object, there is complicated synchronization down to installations (child objects) and vice versa that needs to be done when we update user (mother object).

Is there a better, cleaner way to do this?

Thanks!

1 Answers1

0

Yes, there is a cleaner way. I had this problem a few months ago.

In this scenario of one to many relationships, you can choose between two approaches: RELATION or ARRAY of objects.

If you use a RELATION, as an advantage you have virtually no limit for the items in the relation. However, as a drawback, you need to query the relation to get the information, leading to the approach you mentioned, with many queries.

If you use an ARRAY of objects, as an advantage you can INCLUDE this field in the query, so you will have all the children available with just one query. However, as a drawback, you will be limited to 100 children.

As we are talking about an user and its installations, I think the ARRAY of objects is the best approach for this situation.

Oscar Eduardo
  • 376
  • 1
  • 8