简体   繁体   中英

SailsJS through association: how to create association?

I'm using Sails 0.12.3 and postgresql 9.3.4 on Mac OSX (10.10.5), and I'm attempting to implement a through association

I've set up two models with a third as the join table. When I attempt to test that it is all set up by creating a relationship I get this error:

  Uncaught TypeError: Cannot read property 'via' of undefined 

Here's my test ( mocha/chai ) -- I think the error is actually in this method of creating the association (since if I create the model for the join as a separate call it works:

  describe('with orgs', function() {
    beforeEach(function(done) {
      var testEmail = 'sue@test.com';
      var orgName = 'Awesome Org';
      Org.create({name:orgName})
      .then(function(org) {
        return User.create({username:testEmail, orgs:[org]})
      })
      .then(function(user) {
        done()
      })
      .catch(done);
    });
    it('populates empty list of orgs', function(done) {
      console.log('about to call find');
      User.find().populate('orgs')
      .then(function(users) {
        console.log('users', users);
        var user = users[0]
        assert.isNotNull(user.orgs);
        assert.equal(user.orgs.length, 1);
        done();
      })
      .catch(done);
    });
  });

Here are my models:

User.js:

module.exports = {
  attributes: {
    username : { type: 'email' },
    orgs: {
      collection: 'org',
      via: 'user',
      through: 'orgmembership'
    }
  }
};

Org.js:

module.exports = {
  attributes: {
    name : 'string',
    users: {
      collection: 'user',
      via: 'org',
      through: 'orgmembership'
    }
  },
};

OrgMembership.js:

module.exports = {
  tableName: 'org_membership',
  attributes: {
    user: { model: 'User', columnName: 'user_id', foreignKey: true},
    org: { model: 'Org',  columnName: 'org_id', foreignKey: true}
  }
};

I've posted the whole project on github .

I found this other stackoverflow question , which seems to be doing the same thing, and attempted to follow the same pattern, but it's not working for me.

I would appreciate any pointers or suggestions. Thank you!

Users.js should refer to "users" in the "via" definition in Org.js, the same applies to OrgMembership.js

module.exports = {
  attributes: {
    username : { type: 'email' },
    orgs: {
      collection: 'org',
      via: 'users',
      through: 'orgmembership'
    }
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM