0

My attempt at defining a one-to-one relationship using backbone relational.

B is defined without any dependencies or knowledge of A

var B = Backbone.RelationalModel.extend({

    /* No relationship defined with A */

});

A is then defined, with an attempt to define a one-to-one relationship to B.

var A = Backbone.RelationalModel.extend({

    relations: [

        {

            type: Backbone.HasOne,

            key: 'b',

            relatedModel: B,

            reverseRelation: {

                key: 'a',

                type: Backbone.HasOne

            }

        }]

    /* ... */

});

The backbone relational documentation has this to say about one-to-one relationships:

The default reverseRelation.type for a "HasOne" relation is "HasMany". This can be set to "HasOne" instead, to create a one-to-one relation.

Inspecting the results of this indicates that when I do

var someId = 123;

var myB = B.findOrCreate(someId);

var myA = A.findOrCreate(someId);

Both objects myA and myB are created successfully, with all the expected data.

The related object, however is not there. I want myA.b to reference myB, and it appears that backbone relational has created this key but lefty it undefined.

I have not specified that the "join" is meant to happen using the id attributes of both classes - however I cannot figure out how.

How do I accomplish this?

bguiz
  • 27,371
  • 47
  • 154
  • 243
  • When you define `A`. `B` will be undefined. Try moving the relations to the definition of `B`. (relatedModel: B) – Andreas Louv Jun 18 '13 at 07:05
  • Or it seems that you can string B and that should do it. `relatedModel : 'B'` – Andreas Louv Jun 18 '13 at 07:08
  • @NULL I have updated the question - turns out that I was actually defining B before I was defining A, so this was not the problem... But I still do not know how to specify that `id` should be used as the relationship. – bguiz Jun 18 '13 at 07:11

0 Answers0