Sails.js中的多个关联

我目前正在玩Sails.js beta(v 0.10.0-rc4)中的关联。

我试图将多个数据库关联到一个结果(使用sails-mysql )。

这个关联看起来像这个Post – > TagRelation – > Tag 。 而且当我查询Post表时,我希望返回的对象包含关联的Tag名称。

模型看起来像这样:

 // 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' } }; 

现在,一旦我去了http://localhost:1337/post/1我会得到一个带tag_relations键的JSON对象,其中包含一个TagRelation对象数组,但是有没有办法获得一个实际的Tag对象列表呢?指的是呢? 还是有更好的方法来做到这一点?

Sails为你处理连接表,所以你根本不需要TagRelation模型:

 // 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' } }; 

这样蓝图/post/1将包含所有相关的tags 。 查看关联文档获取更多信息 – 修复了断开的链接。

如果两个模型位于不同的数据库中,则dominant:true标签可让Sails知道关联的哪一边放置了连接表。 当两个模型在同一个数据库中时,我们正在使这个选项可选,但是现在必须明确指定。