【问题标题】:SailsJs Paginate concatenated list of objectsSails Js Pagination连接对象列表
【发布时间】:2016-11-07 04:40:29
【问题描述】:

我的模型可能与另一个模型相关,也可能不相关。这是我的模型结构:

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

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

因此,帖子模型可能会附加到发件人,也可能不会附加到发件人。 sender 可以是用户或 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 分页方法,但是因为我将两个单独的数据库调用连接在一起,所以我不知道该怎么做?

【问题讨论】:

    标签: javascript node.js pagination sails.js waterline


    【解决方案1】:

    您可以将这两个查询与 Waterlines 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]})
    

    并得到相同的结果。

    【讨论】:

    • 我会尝试的,但是如果我试图通过多对多的关系来做到这一点。假设我的帖子可以有很多发件人或没有发件人。以上不适用于此,因为发件人不是 post 表的列,因为它使用连接表。
    • 啊,那我就不知道了,抱歉。您的模型定义是一对多的,所以我认为可以这样做。
    猜你喜欢
    • 2017-04-22
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2014-07-18
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多