Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple associations in Sails.js

I'm currently playing around with associations in Sails.js beta (v 0.10.0-rc4).

I'm trying to relate multiple databases into one result (using sails-mysql).

The association looks like this Post -> TagRelation -> Tag. And I when I query the Post table, I want the returned object to include the associated Tag names.

The models look something like this:

// Post model
var Post = {
    title: 'string',
    body: 'string',
    tag_relations: {
        collection: 'TagRelation'
            via: 'post_id'
    }
};
// Tag Relation model
var TagRelation = {
    post_id: {
        model: 'Post'
    },
    tag_id: {
        model: 'Tag'
    }
};
// Tag model
var Tag = {
    name: 'string',
    tag_relations: {
        collection: 'Tag',
        via: 'tag_id'
    }
};

Now, once I go to http://localhost:1337/post/1 I'll get a JSON object with a tag_relations key, containing an array of TagRelation objects, but is there a way to get a list of actual Tag objects they are referring to instead? Or is there a better way to do this?

like image 443
Johan Dettmar Avatar asked Jan 11 '23 22:01

Johan Dettmar


1 Answers

Sails handles the join table for you, so you don't need the TagRelation model at all:

// Post model
var Post = {
    title: 'string',
    body: 'string',
    tags: {
        collection: 'tag',
        via: 'posts',
        dominant: true // could be on either model, doesn't matter
    }
};

// Tag model
var Tag = {
    name: 'string',
    posts: {
        collection: 'post',
        via: 'tags'
    }
};

This way the blueprint /post/1 will contain all its associated tags. See the association docs for more info - broken link fixed.

The dominant:true tag lets Sails know which side of an association to put the join table on, in case the two models are in different databases. We're working on making this optional when the two models are in the same database, but for now it has to be specified explicitly.

like image 161
sgress454 Avatar answered Jan 19 '23 09:01

sgress454