Luc
Luc

Reputation: 17072

Many-to-many relationship in sails

In my sails application (really newbie to sails), I have 3 models:
- Users (email, password)
- Groups (name)
- Items (name)
I'd like the Groups model to act as a many-to-many relationship between Users and Items, how can this be achieved ?

I'm using sails 0.9.4, I've read the issue #124 regarding the relationship but did not really understand if this can be applied to an existing model (that also contains its own attributes on top of itemId and userId).

Upvotes: 5

Views: 4784

Answers (2)

henlee
henlee

Reputation: 121

If you switch to the v0.10 branch, you can try the following,

// Users.js
module.exports = {
    tableName: 'user',
    attributes: {
        email: 'STRING',
        password: 'STRING',
    }
    items: {
        collection: 'item',
        via: 'users',
        through: 'useritem'
    }
}

// Items.js
module.exports = {
    tableName:'item',
    attributes: {
        name: 'STRING'
    }
    users: {
        collection: 'user',
        via: 'items',
        through: 'useritem'
    }
}

// Groups.js
module.exports = {
  tableName: 'group',
  tables: ['user', 'item'],
  junctionTable: true,

  attributes: {
    id: {
      primaryKey: true,
      autoIncrement: true,
      type: 'integer'
    },
    user_items: {
      columnName: 'user_items',
      type: 'integer',
      foreignKey: true,
      references: 'user',
      on: 'id',
      via: 'item_users',
      groupBy: 'user'
    },
    item_users: {
      columnName: 'item_users',
      type: 'integer',
      foreignKey: true,
      references: 'item',
      on: 'id',
      via: 'user_items',
      groupBy: 'item'
    }
  }
}

I had to go through the code in this file to find out what is going on.

Upvotes: 7

scott
scott

Reputation: 596

As of Sails.js v0.9.4, the framework does not yet support associations.

Balderdash (the developers of Sails) have stated that both associations and transactions are on the roadmap for a production release and have documented a possible API in the #124 issue on GitHub

Currently there is a development branch of Waterline (the ORM adapter that Sails uses) that supports associations, however you may encounter some issues when looking for documentation on the new API

For now, you will have to be creative and look into alternative ways to connect your users and items

Upvotes: 1

Related Questions