Question

I have two classes on Parse.com : Image & User. In User class, I am saving 3 fields Name,Mobile-number & Occupation. In Image class I'm saving images.

I have to create one-to-many relation between these two classes so that I can fetch images with the corresponding mobile-number.

I have created a relation between User class and Image class on parse.com with a column named Mobile in User class. Not able to find how can I fetch the images with that particular mobile number with one-to-many relation. Please help as I have gone thru the documentation. Thanks in advance.

Was it helpful?

Solution

This is just the code to go about. You will have to think about organizing your classes thoughtfully. I am not sure how you intend to go but as far as coding is involved, the following should help.

First get the current user.

ParseUser currentUser = ParseUser.getCurrentUser();

Since, you have "mobile" column as the relation in the User table, get the relation first. Like this.

ParseRelation<ParseObject> relation = currentUser
                                    .getRelation("mobile");

Once you get the relation, get the query on the object who require. In your case, it is the Image Object.

ParseQuery<ParseObject> query = relation.getQuery("Image");

From here, you can customize your query. Eg:

query.getFirstInBackground(new GetCallback<ParseObject>() {
  public void done(ParseObject, ParseException e) {
    if(e == null)
    //your code
    //List<ParseFile> pFileList = (ArrayList<ParseFile>) object.get("images"); //something like this just to give an idea
  }

});

Or if you have multiple objects, use

query.findInBackground(new FindCallback<ParseObject>() {
    public void done(List<ParseObject> list, ParseException e) {
        if (e == null) {
            for (ParseObject object : list) {

                ParseFile image = (ParseFile) object.get("images_column_name");

            }
        } 
    }
});

OTHER TIPS

If an Image class only has one User it is related to, simply use a reference property. You could call it owner or user or whatever. You then just set this to the current user (or any other user).

Internally Parse will store just the ID of this object with some extra information to make this as a link to another class.

When you query you can simply use the current user (or any other user) to compare against that property. Again, Parse will internally just compare ID's, you don't have to think about it.

Look at the documentation here. See where it sets the parent property of the Comment to an instance of the Post? That's the sort of thing you want to do.

Using the mobile number to link is a bad idea, as if you change the number on a User then all the Image classes using that number are now orphaned, unless you write extra code to handle this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top