Sails JS 复杂的多对多关联 [英] Sails JS complex many to many association

查看:37
本文介绍了Sails JS 复杂的多对多关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个模型文件作者、文章和出版物

Let's assume i have Three models files author, article and publications

我的model.js如下

My model.js are as follows

//author.js
attributes : {
 name : 'string',
 articles : {
  collection : 'article',
  via : 'authors'
 }
}

//article.js
attributes : {
 name : 'string',
 authors : {
  collection : 'author',
  via : 'articles'
 },
 publication : {
  model : 'publication'
 }
}

//publication.js
attributes : {
 name : 'string',
 articles : {
  collection : 'article',
  via : 'publication'
 }
}

从上面的关联中,如果我通过他的 ID 获取作者,它将返回作者详细信息,然后是他写的文章,我还想要的是文章必须显示它与发布模型的关联.我无法实现任何建议.

From the above association if i GET an author by his ID,it will return the author details and then the articles which he wrote, what i also want is the articles must show the association which it has with publication model. i couldn't achieve any suggestions please.

我尝试了sails文档,但在那里我只能找到一层关联

I tried the sails documentation but there i can find only one layer of association

我使用 mongodb 作为我的数据库

i'm using mongodb as my database

提前致谢

推荐答案

很抱歉,目前还没有办法在单个数据库查询中完成.您可以在两个或多个数据库查询中执行此操作.例子是这样的.

Sorry to say, but right now there is not way to do it in a single database query. You can do it in two or more database queries. Example would be like this.

Author
.findOne(2)
.populate('articles')
.exec(function (err, itemPost){
    // some error handling
    async.map(itemPost.articles,
        function (article, callback){
            Article
            .findOne(article.id)
            .populateAll()
            .exec(function (errArticles, articleItem){
                if(errArticles){return callback(errArticles)};
                callback(null, articleItem);
            });
        },
        function (errFromIterator, results){
            if(errFromIterator){res.serverError()};

            var itemPostToJSON = itemPost.toJSON();

            itemPostToJSON.comments = results;

            var clone = _.clone(itemPostToJSON);

            res.send(clone);
        }
    )
});

看起来人们已经讨论了很多这个问题.我给你一个他们的讨论 link.我的解决方案也取自那里.希望有帮助.

Looks like people have already discussed this issue a lot. I giving you one of their discussion link. My solution is also taken from there. Hope it helps.

[N.B. : 我没有运行这段代码.所以不能说他们是否是错误的.看起来没问题,所以我把它转给了你.]

[N. B. : I didn't run this code. So can't say if their is a mistake or not. Looked like it's okay so I referred it to you.]

这篇关于Sails JS 复杂的多对多关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆