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.

Y M
  • 2,105
  • 1
  • 22
  • 44

4 Answers4

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() {
  }
});
jeffdill2
  • 3,968
  • 2
  • 30
  • 47
  • 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. – Y M Dec 01 '14 at 07:04
  • It's very awkward to have to create a pointer element, but that does work. Thank you for this. – DiamondDrake Apr 08 '17 at 22:35
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 ...
      }
    });
akarpovsky
  • 316
  • 2
  • 8
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);
    });
});
locropulenton
  • 4,743
  • 3
  • 32
  • 57
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

Tân
  • 1
  • 15
  • 56
  • 102
Chris Li
  • 11
  • 2