繁体   English   中英

SailsJs分页级联的对象列表

[英]SailsJs Paginate concatenated list of objects

我有一个可能与另一个模型无关的模型。 这是我的模型结构:

// Post.js
attributes: {
    sender: { model : 'user' },
}

// User.js
attributes: {
    posts: { collection: 'post', via: 'sender', dominant: true }
}

因此,帖子模型可以是我的,也可以不附加到发件人。 发件人可以是用户,也可以为null。

我需要能够获取特定于特定用户的所有帖子以及没有发件人的所有帖子。 一旦拥有了这两者,就需要将它们连接起来。 这是我要做的代码:

// Before this I use a native query to get a list of posts with no sender. This is "searchIds".
filterData.id = searchIds;
filterData.subject = 1;
posts = [];

        // Populate questions that were sent to all users
        Post.find()
            .where(filterData)
            .exec(function (err, response) {
                if(err) return res.serverError(err);
                // We add all of the posts with no senders to the messages array
                if (response.length > 0){
                    posts = posts.concat(response);
                }

                delete filterData.id;

                // Now we get the posts specific to this user.
                User.findOne({id:id})
                .populate('posts',{ where: filterData })
                .exec(function(err, results){
                  if(err) return res.serverError(err);
                    if (results && results.posts && results.posts.length > 0){
                        posts = posts.concat(results.posts);
                    }
                    return res.json(posts);
                });
        });

这可以找到并让我获得由该特定用户和所有没有发件人的所有帖子组成的数组,但是我现在要做的是分页此列表。 我通常这样做的方法是使用Sails / Waterline分页方法,但是由于我将两个单独的数据库调用串联在一起,所以我不知道该怎么做?

您可以将两个查询与“水线” or要素组合在一起。

Post.find({
    or: {
        {sender: null}, // finds 'no sender' posts
        {sender: senderId} // finds posts where sender's id is senderId 
    }
})
.paginate({ page: 2, limit: 10 })
.then(function(posts) {
    return res.json(posts);
})
.catch(function(err) {
    return res.serverError(err);
})

我很确定您甚至可以像这样编写查找查询

Post.find({sender: [null, senderId]})

并获得相同的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM