How To Retrieve Relation Counts

In the console, child relations columns show a message similar to: “There are nnnn objects referencing this object as a relation.” Given that nnnn is known, is there a way to retrieve it when querying for records, hopefully in one call? I see that Count only works on “real” columns, not incoming relations.

The pattern I’m trying to implement is a common one, simply trying prevent deletion on the client of records that are pointed to by other records.

Thank you!

Hi @Kelly_Oglesby

Assume you have ParentTable with a relation column children to the table ChildTable.
Now if you want to know, how many parent objects are referencing specific child object as a relation, you should make the following query:

DataQueryBuilder queryBuilder = new DataQueryBuilder();
queryBuilder.whereClause =
    "children.objectId = 'YOUR_CHILD_OBJECT_ID'";
queryBuilder.properties = ["Count(objectId)"];
Backendless.data
    .of("ParentTable")
    .find(queryBuilder)
    .then((value) => print(value));

That is the Dart code but I hope you get the point. Let me know if you need the example in another language.

Also I would recommend to read this docs:
Search with the Where Clause
Search with SubQuery

Best Regards,
Maksym

Thank you, that is good to know, but I am trying to count the relations in the opposite direction. I want to download all of the child records, with counts of how many records in 1 to N parent tables have relations to the child records. If the count is > 0, the child record can’t be deleted. In the console, the counts are displayed in the various “RELATION FROM” columns.

Link to Foto

I know I can maintain my own counts (I can use your code snippet to get initial counts) or do queries on the parent tables, I was just thinking there might be a way to access those counts, as shown in this screen capture.

Thanks for your help!

Sorry, just one more example. Given the child table in this foto:

Link to Screenshot

what I would like to do, in pseudo code is:

queryBuilder.properties = [“size”, “Count(vehicles) as refs”]
Backendless.data.of(“ChildTable”).find(queryBuilder)

That throws an error that “vehicles” isn’t a valid column in ChildTable, which is true.

Yes, that is what my code does :slight_smile:

I guest your table is named Vehicle so the code should be:

queryBuilder.whereClause = “backupVehicle.objectId = ‘YOUR_CHILD_OBJECT_ID’”;
queryBuilder.properties = [“Count(objectId)”];
Backendless.data.of(“routes”).find(queryBuilder);

That will return you a count specified in “There are n objects referencing this object as a relation”.

In other words, you should make request to the routes table and look if any “parent” routes objects are referencing to your “child” Vehicle object.

If you have several Parent tables (routes and vehicles I think) you should make several requests to discover if any parent object is referencing to your child object.

Thank you, Maksym, that’s what I will do.

1 Like