Sequelize - Как добиться разбиения на страницы в Nested Queries без использования ассоциации или включает - PullRequest
0 голосов
/ 16 марта 2020

Я использую Sequelize V5.21.5 с node.js, используя приведенный ниже код, я пытаюсь вернуть 10 записей на страницу.

Я использовал смещение и лимит для разбиения на страницы, но мой запрос находится внутри карта (), где на каждой итерации, это дает мне 10 записей. Вместо 10 записей по всем итерациям,

К вашему сведению, я не использую ассоциации и включаю их в таблицы отображения.

Пожалуйста, помогите мне в устранении этой проблемы разбивки на вложенные запросы.

+++++++++++++ Code +++++++++++++

const finalData = await MasterDma.findAll({
      where: whereDMAQuery,
      attributes: ["zipcode", "city"],
      raw: true
    })
      .then(regionData => {
       **//regionData give us multiple zipcodes ["10001","10002","10003","10004","10005"]**

        const promisesHolder = [];
        const limit = 10;

        if (!page) {
          page = 1;
        }

        const offset = (page - 1) * limit;

 //Loops starts here gives us a zipcode from an array on each iteration and this zipcode is passed in where condition.
        regionData.map(data => {
          const bindQuery = { zipcode: data.zipcode, ...whereQuery };

          promisesHolder.push(   

HcpSalaryDetails.findAndCountAll ) находится в l oop, и здесь я использую атрибуты offset, limit для разбивки на страницы, чтобы показать только 10 записей, но ограничение, offset было применено к каждые HcpSalaryDetails. findAndCountAll () в итерации и в целом он дает мне более 10 записей, что неверно.

            HcpSalaryDetails.findAndCountAll({
              raw: true,
              offset: offset,
              limit: limit,
              attributes: [
                "year_exp",
                "dmac",
                "zipcode",
                "age",
                "est_salary",
                "sal_year"
              ],
              where: bindQuery
            }).then(salaryResult => {
              let count = salaryResult.count;
              let salaryDataSet = salaryResult.rows.map(salRecord => {
                return salRecord;
              });
              // returning multiple query counts and data for each iteration 
              return { count, salaryDataSet };
            })
          );
        });
        // multiple promises are pushed to promiseholder array  and returning promise.all with promiseholder array.
        return Promise.all(promisesHolder);
      })
      .then(dataHolder => {
        var totalCount = 0;
        var finalDataHolder = [];
        dataHolder.map(data => {
          totalCount += data.count; // Suming all query counts to one
          finalDataHolder.push(data.salaryDataSet); // pushing multiple promises to array
        });

        return {
          totalCount: totalCount,
          salaryData: [].concat.apply([], finalDataHolder)  //concating multiple array's data to one array
        };
      })
      .catch(err => {
        console.log(err);
      });

    return finalData;

Пожалуйста, помогите мне решить эту проблему.

...