Pulling parent object during query on children

Hello,

I have a one-to-many relationship between two tables, Person and Note, in which one person owns many notes.

I am running a search query on notes, and would like to load properties from the parent object Person during the query. Choosing which properties to load would be optimal, but if that’s not possible, loading the entire object will do and I’ll just parse when I need out of that object.

Is there a way to condense this into one query through the JS SDK, or do I need to split it into two queries?

Previous discussions in this arena:
http://support.backendless.com/t/inverse-of-a-relationship
http://support.backendless.com/t/how-to-get-parent-table-details-from-child-table
https://backendless.com/feature-28-loading-related-data-objects-the-semi-lazy-approach/
https://backendless.com/feature-59-recursive-object-references-in-persistence-objects/

These seem to describe either 1) forward relational querying (getting children loaded when querying parents) or 2) loading the reverse in two steps.

One thing I noticed: my JS model that I downloaded from the server didn’t define a reverse relational property on the Note type. I have tried to manually define this property, but a query against it fails (see below)

[model]
/**
 @name Note#person
 @type Person
 */
this.person = undefined;


[query]
noteQuery.options = { relations: [ 'person' ] };

{ code: 1023,
  message: 'Unable to retrieve data. Query contains invalid object related properties.' }


1 Like

Hi Cameron,

Object retrieval from multiple tables is unidirectional in Backendless. It goes in the direction of the relations, where you retrieve a collection of “parent” objects and may optionally request “children” to be included into the returned hierarchy. A possible workaround is to have relation columns declared in both parent and child tables, where two relations are explicitly declared: from parent to children and from a child to its parent. However, I would not recommend this, as maintaining all the relationships with that approach would turn into a nightmare.

Btw, the reverse relationships must be not declared as properties - only the primordial ones.

Regards,
Mark

Hi Cameron.
You can also use such approach:
make request to child table with additional where clause, that would take into account values of fields from parent table (for proper filtration); and the second query retrieve properties of already known parent objects (from the previous query).

For example you have two tables ‘parent’–<‘child’ that connected through the filed ‘childRel’. ‘parent’ has fields age,name,childRel and the ‘child’ table – ‘toy’ and ‘count’.
The where clause in request to ‘child’ table can be like this: parent[childRel].age > 30
That is we want to retrieve all child objects, which parents are older then 30.

Maybe this would be helpful.

1 Like