Wouter
Wouter

Reputation: 100

Sails js 2:n relation

I recently started working with SailsJS, and I found the process of defining attributes and associations very elegant. However, there is one thing I cannot find out:

I have a model Couple(person1, person2). I'd like to create an association in Person, that lists every couple they are a member of. Something along the lines of:

attributes{
    //other attributes,
    couples:{
        collection: 'couple',
        via: 'person1, person2'
    }
}

My current method is:

attributes{
    //other attributes,
    couples1:{
        collection: 'couple',
        via: 'person1'
    },
    couples2:{
        collection: 'couple',
        via: 'person2'
    },
    getCouples: function() {
        return this.couples1 + this.couples2;
    }
}

But this doesn't seem very pretty, is there a way to do it more elegantly?

Upvotes: 1

Views: 47

Answers (1)

Lu Roman
Lu Roman

Reputation: 2260

If i get your question correctly, you want a person and its couple, i'm assuming you have a monogamous relationship in your couples (meaning one person belongs to the other and vice-versa) you can make an association with the same model, like this.

var Person = {
  attributes: {
      name: {type:'string'},
      couple: {model: 'Person', via: 'couple'}
  }
};

module.exports = Person

Then you can create and associate them like this. (Assuming sails console)

Person.create({name: 'John Doe', couple: {name: 'Jane Doe'} }).exec(console.log)
Person.update(2, {couple:1}).exec(console.log)

And retrieving them is as easy as

Person.find({name:'John Doe'}).populate('couple').exec(console.log)

You can try to associate them with .add and .save but i'm not sure if it works when the association points to the same model, so check that out.

Another option is to have it like this:

var Person = {
  attributes: {
      name: {type:'string'},
      couple: {model: 'Couple', via: 'persons'}
  }
};

module.exports = Person;

Couple model holds a collection of persons, so you can add persons to the couple model, and associate them later with the person.couple attribute.

var Couple = {
  attributes: {
    persons: {collection: 'Person', via: 'couple'}
  }
};

module.exports = Couple;

Or you could use what you have, which is not ideal in this case, but it works.

Upvotes: 1

Related Questions