hasAndBelongsToMany - seeding data question - creating objects

48 views
Skip to first unread message

Steve Gentile

unread,
Mar 27, 2015, 7:45:02 AM3/27/15
to loopb...@googlegroups.com
I'm new to loopback and I'm struggling on how to create objects with relations - most the documentation shows how to wire up the relations but rarely do I see an actual example outside of calling endpoints.


All of them show this 'add' function off the model, ie :

physician.tenants.add(tenant);

I'm getting this error:

"server/boot/script.js:28
            physician.tenants.add(tenant);
                            ^
TypeError: Cannot read property 'add' of undefined"

My setup is:

'A physician is a user'
'A physician belongs to one or more tenants'

('A tenant has many physicians)


Here is my object structure
{
  "name": "Physician",
  "base": "User",
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "tenants": {
      "type": "hasAndBelongsToMany",
      "model": "Tenant",
      "foreignKey": ""
    }
  },
  "acls": [],
  "methods": []
}

My seed code:
var pgPhoenix = app.dataSources.pg;
  pgPhoenix.autoupdate();

  pgPhoenix.automigrate('Tenant', function(err) {
    if (err) return cb(err);
    var Tenant = app.models.Tenant;
    Tenant.create([
      {name: 'Test Tenant'}
    ], function(err, tenant){
        console.log(tenant);
        pgPhoenix.automigrate('Physician', function(err){
          var Physician = app.models.Physician;
          console.log(tenant);
          Physician.create([
            {
              username:'fbar',
              name: 'Foo Bar',
              email:'f...@test.com',
              password: '123123'
            }
          ],function(err, physician){
            physician.tenant.add(tenant);
            //tenant.physicians.add(physician);
            //console.log(physician);
            console.log(physician);
          });
        });
    });
  });

----

Here is the tenant information, not 100% sure if this is setup correctly:
{
  "name": "Tenant",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "physicians": {
      "type": "hasMany",
      "model": "Physician",
      "foreignKey": ""
    }
  },
  "acls": [],
  "methods": []
}

Thanks in advance!
Steve
Reply all
Reply to author
Forward
0 new messages