0

Supposedly I have a database structure like this

Person ('name', 'age')
Belonging ('person', 'type')

with its relationship like this

Person -> Belongings (one to many)

and I want to query all person with their number of belongings included like this

Array[0] -> name, age, numberOfBelongings,
Array[1] -> name, age, numberOfBelongings,
etc

How do I do this? I tried to use CloudCode but, it turned out the fetching method is asynchronous, so I can't fetch the number of belongings to each person.

1 Answer 1

1

You can't do that directly. If you need this count, you could create a field on the Person class (i.e. numberofbelongings) which you update in an afterSave cloud code hook on Belonging. Whenever a Belonging is saved, you also increment the numberofbelongings field on the Person object, and save that as well.

No extra queries, no extra network traffic from your device, and your always have the count available for any Person object.

Sign up to request clarification or add additional context in comments.

3 Comments

Yea, I thought of that too. But it wouldn't be accurate if something happened when afterSave was executed, wouldn't it?
What do you mean by "happened"? You could run into concurrency-problems if a Person's belongings were changing very rapidly, but that does not seem likely. What did you have in mind?
yes, concurrency problem is what I have in mind. hahaha.. Ok, i'll try your suggestion. Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.