Sails JS complex many to many association

丶灬走出姿态 提交于 2020-01-24 12:04:01

问题


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

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

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.

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

i'm using mongodb as my database

Thanks in advance


回答1:


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);
        }
    )
});

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. : 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.]



来源:https://stackoverflow.com/questions/30324302/sails-js-complex-many-to-many-association

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!