Query on pointer in parse.com Objects in Javascript
Asked Answered
L

4

16

I have a Class of Company which has User pointers. The query I want on Company class is like this:

Retrieve Company rows where User object has a name equal to 'ABC'

So, how should I form this query ?

var Company = Parse.Object.extend("Company");
var query = Parse.Query(Company);
query.include("User");

query.equalTo("name")       ????

Is it possible to write such a request in a single query ? Thanks.

Living answered 14/11, 2014 at 4:56 Comment(0)
S
19

You'll need to query for the User first based on the name of "ABC". Then in the success callback of that query, do the query on your Company table using the objectId returned from the User query. Something like this:

var userQuery = Parse.Query('_User');
var companyQuery = Parse.Query('Company');

userQuery.equalTo('name', 'ABC');

userQuery.find({
  success: function(user) {
    var userPointer = {
      __type: 'Pointer',
      className: '_User',
      objectId: user.id
    }

    companyQuery.equalTo('user', userPointer);

    companyQuery.find({
      success: function(company) {
        // WHATEVER
      },
      error: function() {
      }
    });
  },
  error: function() {
  }
});
Spectroscope answered 1/12, 2014 at 1:30 Comment(2)
Hi, thanks for answering.. I asked because I needed to know if this is possible in a single query.. Similar to inner queries in MySql.Living
It's very awkward to have to create a pointer element, but that does work. Thank you for this.Mountbatten
O
12

You can use an inner query:

var Company = Parse.Object.extend("Company");
var mainQuery = Parse.Query(Company);

var UserObject = Parse.Object.extend("User");
var innerUserQuery = new Parse.Query(UserObject);
innerBankQuery.equalTo("name", "ABC");
mainQuery.matchesQuery("bank", innerBankQuery);

var ansCollection = mainQuery.collection();
    ansCollection.fetch({
        success: function(results) {
         // Do whatever ...
      }
    });
Optimistic answered 10/2, 2015 at 4:9 Comment(1)
What is innerBankQuery in your example?Fireeater
S
4

I should say the query will be...

const userQuery = Parse.Query('_User');

userQuery.equalTo('name', 'ABC');

userQuery.find().then((user) => {

    const companyQuery = Parse.Query('Company');

    companyQuery.equalTo('user', {
      __type: 'Pointer',
      className: '_User',
      objectId: user.id
    });

    companyQuery.find().then((company) => {
        console.log(company);
    });
});
Salem answered 22/2, 2017 at 16:51 Comment(0)
N
1

Assuming Your Company collection has a field called User and User collection has a name field, then you can search for Company with user name through companyQuery.equalTo("User.name");

This works in Parse 2.1.0

Nubbly answered 11/11, 2018 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.