簡體   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