【问题标题】:Multiple associations in Sails.jsSails.js 中的多个关联
【发布时间】:2014-05-03 13:59:42
【问题描述】:

我目前正在使用 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 对象的列表他们指的是?或者有更好的方法吗?

【问题讨论】:

    标签: javascript node.js associations sails.js


    【解决方案1】:

    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。有关更多信息,请参阅association docs - 已修复断开的链接。

    dominant:true 标签让 Sails 知道将连接表放在关联的哪一侧,以防两个模型位于不同的数据库中。当两个模型在同一个数据库中时,我们正在努力将其设为可选,但现在必须明确指定。

    【讨论】:

    • 我明白了!这似乎工作正常!除了纯 mysql 查询之外,是否可以计算有多少“关系”?此外,如果我不想为关系存储额外数据(即用户标记它等),这可能吗?
    • Sails 目前不支持has-many-through 关系,这将允许您存储有关该关系的额外数据,尽管它正在开发中。至于计算关系,你可以做Post.findOne(1).populate('tags').exec(function(err, post){console.log(post.tags.length);})。有关更多信息,请参阅populate 的文档。
    • 所有文档现在都在sailsjs.org 上更新。关联之一是here。在答案中也进行了编辑。
    猜你喜欢
    • 2015-06-27
    • 2014-12-01
    • 2015-06-07
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    相关资源
    最近更新 更多