【问题标题】:Chaining Association With Waterline与水线的链接关联
【发布时间】:2014-10-17 11:23:57
【问题描述】:

我有 3 个模型:提要、链接和来源。

每个提要都有一对多关联的链接。

Feed.js:

links: {
    collection: 'link',
    via: 'feed'
}

并通过一对一关联将模型连接到源模型。

Link.js:

source: {
    model: 'source'
}

源模型中没有什么特别的东西。

当我执行下面的查询时,我无法获取源模型中定义的链接的详细信息。

Feed.find({}).populate('links').exec(console.log);

结果:

{
 links: 
 [
 {
    title: 'News link',
    url: 'http://href.com/sfs',
    feed: 1,
    source: 1,
    id: 1,
    createdAt: '2014-08-23T13:01:42.989Z',
    updatedAt: '2014-08-23T13:01:42.989Z'
}
],
title: 'Feed Title',
photo: 'img/img.png',
yesNo: false,
id: 1,
createdAt: '2014-08-23T13:00:43.317Z',
updatedAt: '2014-08-23T13:00:43.317Z' 
} 

我想用源模型填充“链接”集合。是否可以使用 Waterline 或我必须手动完成?

谢谢,

【问题讨论】:

    标签: database orm sails.js waterline


    【解决方案1】:

    水线种群目前只有一层深;多层次人口在路线图上。目前最好的办法是在填充链接的情况下进行初始Feed 查询,从Link 记录中收集所有source 外键,一次找到它们,然后进行映射。比如:

    async.auto({
    
        // Get all feeds
        feeds: function(cb) {
    
            Feed.find({}).populate('links').exec(cb);
    
        },
    
        // Get all sources of feed links
        sources: ['feeds', function(cb, results) {
    
            var sourceIds = results.feeds.reduce(function(memo, feed) {
    
                return memo.concat(_.pluck(feed.links, 'source'));                       
    
            }, []);
    
            Source.find(sourceIds).exec(cb);
    
        }],
    
        // Map source objects onto links
        mapping: ['feeds', 'sources', function(cb, results) {
    
            // Index sources by ID
            var sources = _.indexBy(results.sources, 'id');
    
            var feeds = results.feeds.map(function(feed) {
    
                feed.links = feeds.links.map(function(link) {
    
                    link.source = sources[link.source];
                    return link;
    
                });
    
                return feed;
    
            });
    
            return cb(null, feeds);
    
        }]
    
    }, function done(err, results) {
    
       // Handle err or do something with results.mapping
    
    });
    

    【讨论】:

    • 感谢您的回答。我对节点/帆太陌生,需要一些工作才能理解。但这似乎是目前最好的方法。 :)
    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多