Skip to content

Limit on nested hasMany include returns no data #9651

Open

Description

@rsispal

Hi,

I am seeking some assistance with the use of limit on a nested hasMany include. It simply returns an empty object even though there’s actually data that should be returned.

I’ve looked through SO and the Github issues and it seems others have had similar problems and used things like distinct: true and subQuery: false to get around it - none of which have worked for me. Lots of these issues just pass me around in circles between the same posts.

I am at a loss as to whether this is a bug or if it’s something I am doing wrong, so would be great to hear for certain. I really need this limitation on specific includes as there could be hundreds of records that could possibly be returned, even though I only need the most recent 5. I can manually fetch this data, but that means more queries and processing time, then manual processing to "connect" the data back into the right places.

What are you doing?

Here is the query that has the issue:

// const references = ['PANEL00001', 'PANEL00002', 'PANEL00003']
return LocalDB.Panels
            .findAll({
                where: { reference: references },
                include: [
                    {
                        model: LocalDB.PanelEvents,
                        order: [['timestamp', 'DESC']],
                        limit: 3 //<- DOES NOT WORK - causes query to return [{}]
                    },
                    {
                        model: LocalDB.Communicators,
                        include: [
                            {
                                model: LocalDB.CommunicatorStatusUpdates,
                                order: [['timestamp', 'DESC']],
                                limit: 1 //<- DOES NOT WORK - causes query to return [{}]
                            }
                        ]
                    }
                ],
                returning: true,
                logging: false
            })

I made a full test example, which you can get here. Switch to branch 1-limit-does-not-apply-on-nested-findall on that repository and read the readme to connect to a local PG database.

What do you expect to happen?

I want to be able to apply a limit on a nested include and it return that specific number of records.

What is actually happening?

  • With the limits in place on PanelEvents and CommunicatorStatusUpdates, all that gets returned for those specific includes is [{}]
  • Without the limits in place, I run up my server and database costs by requesting 00's of records when they aren't all needed.
[
    {
        "id": 1,
        "reference": "PANEL00001",
        "model": "PANEL-X",
        "status": "ACTIVE",
        "created_at": "2018-07-11T00:00:01.000Z",
        "updated_at": "2018-07-11T00:00:01.000Z",
        "Communicators": [
            {
                "id": 1,
                "reference": "COMMUNICATO0001",
                "model": "MODEL-A",
                "panelReference": "PANEL00001",
                "created_at": "2018-07-11T00:00:01.000Z",
                "updated_at": "2018-07-11T00:00:01.000Z",
                "CommunicatorStatusUpdates": [
                    {}
                ]
            }
        ],
        "PanelEvents": [
            {}
        ]
    },
    {
        "id": 2,
        "reference": "PANEL00002",
        "model": "PANEL-Y",
        "status": "ACTIVE",
        "created_at": "2018-07-11T00:00:01.000Z",
        "updated_at": "2018-07-11T00:00:01.000Z",
        "Communicators": [
            {
                "id": 2,
                "reference": "COMMUNICATO0002",
                "model": "MODEL-B",
                "panelReference": "PANEL00002",
                "created_at": "2018-07-11T00:00:01.000Z",
                "updated_at": "2018-07-11T00:00:01.000Z",
                "CommunicatorStatusUpdates": [
                    {}
                ]
            }
        ],
        "PanelEvents": [
            {}
        ]
    },
    {
        "id": 3,
        "reference": "PANEL00003",
        "model": "PANEL-Z",
        "status": "ACTIVE",
        "created_at": "2018-07-11T00:00:01.000Z",
        "updated_at": "2018-07-11T00:00:01.000Z",
        "Communicators": [
            {
                "id": 3,
                "reference": "COMMUNICATO0003",
                "model": "MODEL-C",
                "panelReference": "PANEL00003",
                "created_at": "2018-07-11T00:00:01.000Z",
                "updated_at": "2018-07-11T00:00:01.000Z",
                "CommunicatorStatusUpdates": [
                    {}
                ]
            }
        ],
        "PanelEvents": [
            {}
        ]
    }
]

Dialect: postgres
Dialect version: PostgreDB 9.6.6 (node pg: 7.4.3)
Database version: PostgreDB 9.6.6 (node pg: 7.4.3)
Sequelize version: 4.38.0
Tested with latest release: 4.38.0

Reading prior to posting this issue:
#9188
#7344
#1897
#6891
https://stackoverflow.com/questions/31309369/sequelize-limit-and-order-inside-an-include-construct

Activity

  1. rsispal commented on Jul 30, 2018

    @rsispal
    Author

    18 days later...nobody?

  2. seblemeur commented on Jul 30, 2018

    @seblemeur

    Same problem ...

  3. dietrichg commented on Aug 27, 2018

    @dietrichg

    Same problem.

  4. seblemeur commented on Aug 27, 2018

    @seblemeur

    @dietrichg , I found the solution by updating at 4.38.0 sequelize.

  5. rsispal commented on Aug 30, 2018

    @rsispal
    Author

    My example project is using 4.38.0 and there is still an issue..

  6. darkotuning commented on Oct 13, 2018

    @darkotuning

    Same problem....

  7. kluchy-dev commented on Feb 4, 2019

    @kluchy-dev

    Same issue:

    This works:

    OTPs.findAll({
          limit: limit,
          subQuery: false,
          where: {
            Type: 2,
          },
          attributes: ['DTSale'],
          include: [
            {
              model: OTPVehicles,
              as: 'OTPVehicle',
              attributes: {
                exclude: ['VehicleImage'],
              },
              required: true,
            },
            {
              model: Prospects,
              as: 'Prospect',
              attributes: ['ID'],
              include: [
                {
                  model: Contacts,
                  as: 'Contact',
                  required: true,
                },
                {
                  model: Franchises,
                  as: 'Franchise',
                  where: {
                    ID: franchiseId,
                  },
                  attributes: [],
                },
              ],
              required: true,
            },
          ],
        });
    

    But when I add offset it does not work:

    OTPs.findAll({
          limit: limit,
          offset: offset,
          subQuery: false,
          where: {
            Type: 2,
          },
          attributes: ['DTSale'],
          include: [
            {
              model: OTPVehicles,
              as: 'OTPVehicle',
              attributes: {
                exclude: ['VehicleImage'],
              },
              required: true,
            },
            {
              model: Prospects,
              as: 'Prospect',
              attributes: ['ID'],
              include: [
                {
                  model: Contacts,
                  as: 'Contact',
                  required: true,
                },
                {
                  model: Franchises,
                  as: 'Franchise',
                  where: {
                    ID: franchiseId,
                  },
                  attributes: [],
                },
              ],
              required: true,
            },
          ],
        });
    

    It generates:

    SELECT TOP 100 PERCENT [OTP].[id], 
                           [OTP].[dtsale], 
                           [otpvehicle].[otpid]                           AS 
                           [OTPVehicle.OTPID], 
                           [otpvehicle].[vehicleid]                       AS 
                           [OTPVehicle.VehicleID], 
                           [otpvehicle].[make]                            AS 
                           [OTPVehicle.Make], 
                           [otpvehicle].[model]                           AS 
                           [OTPVehicle.Model], 
                           [otpvehicle].[modelcode]                       AS 
                           [OTPVehicle.ModelCode], 
                           [otpvehicle].[modelyear]                       AS 
                           [OTPVehicle.ModelYear], 
                           [otpvehicle].[colour]                          AS 
                           [OTPVehicle.Colour], 
                           [otpvehicle].[kms]                             AS 
                           [OTPVehicle.KMS], 
                           [otpvehicle].[engineno]                        AS 
                           [OTPVehicle.EngineNo], 
                           [otpvehicle].[chassisno]                       AS 
                           [OTPVehicle.ChassisNo], 
                           [otpvehicle].[serialno]                        AS 
                           [OTPVehicle.SerialNo], 
                           [otpvehicle].[vin]                             AS 
                           [OTPVehicle.VIN], 
                           [otpvehicle].[regno]                           AS 
                           [OTPVehicle.RegNo], 
                           [otpvehicle].[keycode]                         AS 
                           [OTPVehicle.KeyCode], 
                           [otpvehicle].[radiocode]                       AS 
                           [OTPVehicle.RadioCode], 
                           [otpvehicle].[meadm]                           AS 
                           [OTPVehicle.MeadM], 
                           [otpvehicle].[nscno]                           AS 
                           [OTPVehicle.NSCNo], 
                           [otpvehicle].[stockno]                         AS 
                           [OTPVehicle.StockNo], 
                           [otpvehicle].[dtregistered]                    AS 
                           [OTPVehicle.DTRegistered], 
                           [otpvehicle].[type]                            AS 
                           [OTPVehicle.Type], 
                           [otpvehicle].[dtcreated]                       AS 
                           [OTPVehicle.DTCreated], 
                           [otpvehicle].[dtupdated]                       AS 
                           [OTPVehicle.DTUpdated], 
                           [otpvehicle].[empidcreated]                    AS 
                           [OTPVehicle.EmpIdCreated], 
                           [otpvehicle].[empidupdated]                    AS 
                           [OTPVehicle.EmpIdUpdated], 
                           [otpvehicle].[averagekms]                      AS 
                           [OTPVehicle.AverageKms], 
                           [otpvehicle].[financeterm]                     AS 
                           [OTPVehicle.FinanceTerm], 
                           [otpvehicle].[interestrate]                    AS 
                           [OTPVehicle.InterestRate], 
                           [otpvehicle].[monthlyservicefee]               AS 
                           [OTPVehicle.MonthlyServiceFee], 
                           [otpvehicle].[initiationfee]                   AS 
                           [OTPVehicle.InitiationFee], 
                           [otpvehicle].[vehiclesource]                   AS 
                           [OTPVehicle.VehicleSource], 
                           [otpvehicle].[cdkvehicleid]                    AS 
                           [OTPVehicle.CdkVehicleId], 
                           [prospect].[id]                                AS 
                           [Prospect.ID], 
                           [Prospect->Contact].[id]                       AS 
                           [Prospect.Contact.ID], 
                           [Prospect->Contact].[guid]                     AS 
                           [Prospect.Contact.GUID], 
                           [Prospect->Contact].[type]                     AS 
                           [Prospect.Contact.Type], 
                           [Prospect->Contact].[companyname]              AS 
                           [Prospect.Contact.CompanyName], 
                           [Prospect->Contact].[companyregno]             AS 
                           [Prospect.Contact.CompanyRegNo], 
                           [Prospect->Contact].[companytrafficregno]      AS 
                           [Prospect.Contact.CompanyTrafficRegNo], 
                           [Prospect->Contact].[companyvatno]             AS 
                           [Prospect.Contact.CompanyVATNo], 
                           [Prospect->Contact].[companyindustrytype]      AS 
                           [Prospect.Contact.CompanyIndustryType], 
                           [Prospect->Contact].[firstname]                AS 
                           [Prospect.Contact.FirstName], 
                           [Prospect->Contact].[lastname]                 AS 
                           [Prospect.Contact.LastName], 
                           [Prospect->Contact].[title]                    AS 
                           [Prospect.Contact.Title], 
                           [Prospect->Contact].[idno]                     AS 
                           [Prospect.Contact.IdNo], 
                           [Prospect->Contact].[language]                 AS 
                           [Prospect.Contact.Language], 
                           [Prospect->Contact].[race]                     AS 
                           [Prospect.Contact.Race], 
                           [Prospect->Contact].[gender]                   AS 
                           [Prospect.Contact.Gender], 
                           [Prospect->Contact].[dtbirthday]               AS 
                           [Prospect.Contact.DTBirthday], 
                           [Prospect->Contact].[prefcontactphonenotype]   AS 
                           [Prospect.Contact.PrefContactPhoneNoType], 
                           [Prospect->Contact].[email]                    AS 
                           [Prospect.Contact.Email], 
                           [Prospect->Contact].[dtfirstcontact]           AS 
                           [Prospect.Contact.DTFirstContact], 
                           [Prospect->Contact].[replacementpolicyyears]   AS 
                           [Prospect.Contact.ReplacementPolicyYears], 
                           [Prospect->Contact].[replacementpolicykms]     AS 
                           [Prospect.Contact.ReplacementPolicyKMS], 
                           [Prospect->Contact].[affordablepaymentbracket] AS 
                           [Prospect.Contact.AffordablePaymentBracket], 
                           [Prospect->Contact].[preferredfinanceoption]   AS 
                           [Prospect.Contact.PreferredFinanceOption], 
                           [Prospect->Contact].[mayreceivecorrespondence] AS 
                           [Prospect.Contact.MayReceiveCorrespondence], 
                           [Prospect->Contact].[grading]                  AS 
                           [Prospect.Contact.Grading], 
                           [Prospect->Contact].[dmsref]                   AS 
                           [Prospect.Contact.DMSRef], 
                           [Prospect->Contact].[dtcreated]                AS 
                           [Prospect.Contact.DTCreated], 
                           [Prospect->Contact].[dtupdated]                AS 
                           [Prospect.Contact.DTUpdated], 
                           [Prospect->Contact].[empidcreated]             AS 
                           [Prospect.Contact.EmpIdCreated], 
                           [Prospect->Contact].[empidupdated]             AS 
                           [Prospect.Contact.EmpIdUpdated], 
                           [Prospect->Contact].[passportno]               AS 
                           [Prospect.Contact.PassportNo] 
    FROM   (SELECT TOP 3 * 
            FROM   (SELECT Row_number() 
                             OVER ( 
                               ORDER BY [id]) AS row_num, 
                           * 
                    FROM   [otp] AS [OTP] 
                    WHERE  [otp].[type] = 2) AS [OTP] 
            WHERE  row_num > 1) AS [OTP] 
           INNER JOIN [otpvehicle] AS [OTPVehicle] 
                   ON [OTP].[id] = [otpvehicle].[otpid] 
           INNER JOIN [prospect] AS [Prospect] 
                   ON [OTP].[prospectid] = [prospect].[id] 
           INNER JOIN [contact] AS [Prospect->Contact] 
                   ON [prospect].[contactid] = [Prospect->Contact].[id] 
           INNER JOIN [franchise] AS [Prospect->Franchise] 
                   ON [prospect].[franchiseid] = [Prospect->Franchise].[id] 
                      AND [Prospect->Franchise].[id] = 107 
    WHERE  [OTP].[type] = 2;
    

    Dialect: mssql - tedious
    Sequelize version: 4.42.0
    Database version: MSSQL Server 2008 R2 v10.50.1600.1

  8. stale commented on May 5, 2019

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  9. rsispal commented on May 5, 2019

    @rsispal
    Author

    8 months later and this is still an issue. Having to manually retrieve records with a limit separately which is cumbersome.

    Anyone else still having this problem too?

  10. snax4a commented on Sep 10, 2019

    @snax4a

    I have same issue, when I do .findOne and include hasMany model it is generating only one SQL query with LEFT OUTER JOIN and it returns me source model data and target model data but when I will add limit parameter to include object it is making two queries one for the source model and one for the target model - both queries are correct and return data but sequelize gives me empty data for the included model

  11. added
    type: bug
    on Sep 14, 2019
  12. papb commented on Sep 14, 2019

    @papb
    Member

    @rsispal Thanks for the detailed report and for providing a SSCCE. Unfortunately I don't have time to look into it right now...

    Lots of these issues just pass me around in circles between the same posts.

    Can you please post all those links you think are related? Thanks

  13. rsispal commented on Sep 15, 2019

    @rsispal
    Author

    All the details are available in the original post, including the cycle links.

    I’ve stopped using Sequelize now because of this and how ambiguous parts of the docs are.

    That said, I’m sure others above can continue to assist

  14. papb commented on Sep 15, 2019

    @papb
    Member

    Oops, you are right, sorry about that!! Thank you very much.

  15. barrydevp commented on Nov 21, 2019

    @barrydevp

    anyone fix this issue?

  16. rsispal commented on Nov 21, 2019

    @rsispal
    Author

    Still not working as intended with the latest version.

  17. barrydevp commented on Nov 24, 2019

    @barrydevp

    Still not working as intended with the latest version.

    hey bro, what is your replacement for this?

  18. added
    topic: limit & offset
    on Jan 15, 2020
  19. kevingilbert100 commented on Mar 22, 2020

    @kevingilbert100

    Still an issue.

  20. HevertonPires commented on Oct 3, 2020

    @HevertonPires

    I still have the same problem in version 5.22.3

  21. oaayoub commented on May 29, 2024

    @oaayoub

    this issue still have not been fixed !

  22. added theissue type on Mar 9, 2025
  23. removed
    type: bug
    on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: limit & offset

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions