4

Updated, response to suggested answer provided, awaiting response before bounty award.

Using Parse.com and JavaScript SDK.

I appear unable to solve this, so will put it out to bounty. For the bounty I'd like a code example/solution that solve the problem and that I can learn from.

The below code saves an object to the "mybadges" class. I'd like to have either a pointer or relation in the "FriendRequest" class connected to the mybadges class. Meaning that when I click on the pointer or relation in "FriendRequests" it returns all of the objects uploaded into the myBadges class. I then want to be able to access this data via a query.

Using Parse.com and JavaScript SDK.

Parse.initialize("xxx", "xxx");

                var user = Parse.User.current();

                var MyBadges = Parse.Object.extend("myBadges");
                var userbadges = new MyBadges();

                var Friends = Parse.Object.extend("FriendRequest");
                var friends = new Friends();

                //var Badges = Parse.Object.extend("myBadges");


                //var Badges = Parse.Object.extend("myBadges");

                    $(document).ready(function () {

                    $("#send").click(function () {

                        var badgeselected = $('#badgeselect .go').attr("src");
                        userbadges.set("BadgeName", badgeselected);
                        userbadges.set("uploadedBy", user);
                        //friends.set("status");
                        //friends.save();

                        userbadges.save(null, {
                            success: function (results) {
                        // The object was saved successfully.

                        friends.relation('Friends').add(userbadges);
                        //friends.save();
                        console.log(user);

                        //location.reload();
                    },
                    error: function (contact, error) {
                        // The save failed.
                        // error is a Parse.Error with an error code and description.
                        alert("Error: " + error.code + " " + error.message);
                    }
                });
                    });
                });


                                    $(document).ready(function() {
                    $('.go').css('cursor', 'pointer');
            $('.go').click(function(e) { // Button which will activate our modal
                $(this).width(100).height(100).appendTo('#badgeselect');


                $('#modal').reveal({ // The item which will be opened with reveal
                    animation: 'fade',                   // fade, fadeAndPop, none
                    animationspeed: 600,                       // how fast animtions are
                    closeonbackgroundclick: true,              // if you click background will modal close?
                    dismissmodalclass: 'close'    // the class of a button or element that will close an open modal


                });
                return false;
               });
        });

enter image description here

enter image description here

1 Answer 1

4
+150

To create a one-to-many relationship there are a couple of options:

  • Use "back reference" links, i.e. add a friendRequest pointer to your myBadges class (only supports one-to-many)
  • Add a column of type Array (good for small lists, supports many-to-many)
  • Add a column of type Relation (use queries to navigate, supports many-to-many)
  • Create a custom class to hold the relationships (if you have other data about each join, supports many-to-many) The simplest option is using the Array column, in JavaScript you just use a normal array that contains myBadges instances and assign it to a property of your parent class.

Note: In my examples below, I'm going to change the case of call classes to UpperCamel singular (myBadges -> MyBadge) and all properties/column names to lowerCamel (BadgeName -> badgeName) for consistency, and I suggest you do the same.

Examples:

Common code assumed in the below:

var FriendRequest = Parse.Object.extend("FriendRequest");
var MyBadge = Parse.Object.extend("MyBadge");
var friendRequest = /* some FriendRequest you've loaded */

Option 1 - back-reference

Adding new badge to a friend request:

// MyBadge.friendRequest: Pointer (to FriendRequest)
var myBadge = new MyBadge();
myBadge.set({
    badgeName: someStringVariable,
    uploadedBy: someUserObject,
    friendRequest: friendRequest
});
myBadge.save();

Getting badges for a friend request:

var badgesQuery = new Parse.Query(MyBadge);
badgesQuery.equalTo('friendRequest', friendRequest);
badgesQuery.find({
    success: function(badges) {
        // use badges as needed...
    }
});

Showing MyBadge rows for FriendRequest parent in Data Browser:

Get the objectId of a FriendRequest row, then on the view for MyBadge add a filter on the friendRequest column and paste the ID.


Option 2 - Array

Adding new badge to a friend request:

// FriendRequest.badges: Array (of MyBadge)

// 2-step process, first create and save the MyBadge instance
var myBadge = new MyBadge();
myBadge.set({
    badgeName: someStringVariable,
    uploadedBy: someUserObject
});
myBadge.save()
// step 2 (using chaining here) attach the saved badge to the friend request
.then(function() {
    friendRequest.badges.addUnique(myBadge);
    // return promise to allow further chaining
    return friendRequest.save();
});

Getting badges for a friend request:

// just include them when querying for FriendRequest objects
friendRequestQuery.include('badges');

Showing MyBadge rows for FriendRequest parent in Data Browser:

No support for this, you'll need to create your own solution.


Option 3 - Relation

Adding new badge:

// FriendRequest.badges: Relation (of MyBadge)

// 2-step process, first create and save the MyBadge instance
var myBadge = new MyBadge();
myBadge.set({
    badgeName: someStringVariable,
    uploadedBy: someUserObject
});
myBadge.save()
// step 2 (using chaining here) attach the saved badge to the friend request
.then(function() {
    var badgesRelation = friendRequest.relation('badges');
    badgesRelation.add(myBadge);
    // return promise to allow further chaining
    return friendRequest.save();
});

Getting badges for a friend request:

// query the relation
var badgesRelation = friendRequest.relation('badges');
var badgesQuery = badgesRelation.query();
// apply any filters as you would for any normal Parse.Query()
// ...
// use find() or any other query method
badgesQuery.find({
    success: function(badges) {
        // use array of badges...
    }
})

Showing MyBadge rows for FriendRequest parent in Data Browser:

Double-click on a value in the badges column.


Option 4 - custom join class

This isn't really suitable for your use-case, so I'm not going to provide a sample here.

Sign up to request clarification or add additional context in comments.

9 Comments

Thank you again, are you saying its not suitable to use a pointer for the above? the parse docs seem to suggest it is? parse.com/docs/js_guide#objects-pointers I also understood using an array could be limiting if the child objects numbered over 100+ ?
A pointer is for a pointer to a single object. An array can contain multiple pointers. If you're going to have more than 100 children, look at using a Relation, there's plenty of docs that explain how to use a Relation that you should read first, then post another question if you're still stuck.
I've added a bounty to solve this as I'm banging my head against a wall. See the updated question if your interested.
@Dano007 I added some sample code, I strongly recommend using a back-reference in the scenario you've given.
thanks for the detailed answers, I think these will help the SO community greatly. Regarding my issues, I've followed option 1. I need some validation of what I've done, there fore see the following jfiddles that hold the code for saving and pulling the badges. Could you validate these are correct. jsfiddle.net/Dano007/Lst76/3 and jsfiddle.net/Dano007/HSne9/1/I've added images of the DO structure to make sure this is correct? Perhaps we could discuss this on "chat" if your free today? might solve it quicker.. Many thanks –
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.