Query on pointer in parse.com Objects in Javascrip

2019-06-15 01:59发布

问题:

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.

回答1:

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() {
  }
});


回答2:

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 ...
      }
    });


回答3:

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);
    });
});


回答4:

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