Skip to content

how to set findall include model limit? #1897

Description

@youxiachai
  DB.Article.findAll({
        include : [{model : DB.User, limit 5}],
        order : 'article.created_at DESC',
        limit : 50
    }).done(function (err, result){

        })

i found include limit no effort.

Activity

  1. changed the title [-]how to limit findall include limit[/-] [+]how to set findall include model limit?[/+] on Jun 13, 2014
  2. mickhansen commented on Jun 13, 2014

    @mickhansen
    Contributor

    It's not supported and is not likely to ever be.
    How would a limit like that even work honestly? We already do a subquery to limit the inner row, we would have to do a id fetch subquery for the join row to be able to limit it.

    Can you suggest how a SQL query that achieves what you want might look?

  3. alekbarszczewski commented on Jun 14, 2014

    @alekbarszczewski
    Contributor

    Maybe it could be achieved by joining through SELECT subquery. So instead of:

    SELECT "Table1"."id" AS "Table1.id", "Table2"."id" AS "Table2.id"
    FROM "Table1"
    LEFT JOIN "Table2"
    ON "Table1"."id" = "Table2"."Table1Id"
    LIMIT 50
    

    This query which generates join table base on join conditions

    SELECT "Table1"."id" AS "Table1.id", "Table2"."id" AS "Table2.id"
    FROM "Table1"
    LEFT JOIN (
      SELECT * FROM "Table2" WHERE "Table2"."Table1Id" = "Table1"."id" LIMIT 5
    ) AS "Table2"
    ON "Table1"."id" = "Table2"."Table1Id"
    LIMIT 50
    

    I am not sure it thats is going to work, but if yes then it would be very handy feature :)

  4. mickhansen commented on Jun 16, 2014

    @mickhansen
    Contributor

    @alekbarszczewski hmm, perhaps that could indeed work.

  5. Roam-Cooper commented on Jul 2, 2014

    @Roam-Cooper

    I know I have been neglecting the other issues that I have open, work has picked up and made me rather busy. But I am very interested in being able to limit an include as well. :)

    In fact, limiting an include is integral to our app's functionality, otherwise I will have to do it by looping through and doing another query for each result of the first query.

    The action I have been attempting is that I want to findAll of a user object, but include the most recent of a user:many association. Previously I have ordered by createdAt and used limit 1, but I cannot do this with an include.

    The way that Alek said to do it is the way that most people seem to be doing it as in http://stackoverflow.com/questions/13525656/limit-a-left-join-on-the-first-table and many other stackoverflow threads.

  6. mickhansen commented on Jul 3, 2014

    @mickhansen
    Contributor

    @Roam-Cooper yeah that's likely the way we go, but it has to support where clauses in there aswell so it's a completely new set of logic in the join statements - So not entirely trivial, but doable.

  7. Roam-Cooper commented on Jul 6, 2014

    @Roam-Cooper

    @mickhansen I'd make an attempt at doing it myself, but I've never had a look at the internals of Seq before. :)

  8. seth-admittedly commented on Jul 7, 2014

    @seth-admittedly
    Contributor

    This would hopefully also resolve #1756

  9. mickhansen commented on Jul 7, 2014

    @mickhansen
    Contributor

    @seth-admittedly Hmm, unfortuneatly i don't think so.

  10. kmsheng commented on Oct 8, 2014

    @kmsheng

    I need this, too.

  11. luccasmaso commented on Nov 14, 2014

    @luccasmaso

    +1

  12. daimajia commented on Nov 20, 2014

    @daimajia

    need += 1

  13. vilmosioo commented on Nov 28, 2014

    @vilmosioo

    +1

  14. kdelemme commented on Nov 28, 2014

    @kdelemme

    This would be an awesome feature!

  15. 40 remaining items

  16. ernani commented on Aug 19, 2017

    @ernani

    Same here, I have a belongsToMany relation of orders and order changes, where I keep in orders its id, and order changes, anything that changes for that order, keeping a history of changes.

    But, in my view I just need the latest change, so, I can limit my order history include through an order clause on created_at, desc then limit it to 1.

    Is that possible today? Could not find it in the docs.

    As of now I order by desc, iterate through its elements , get the last one by index, and ignore previous ones.

    I wouldn't want to do that as the more histories I get, more ram I will need to load the info, having it limited to 1 makes more sense.

  17. AntonAL commented on Apr 10, 2018

    @AntonAL

    I also need to limit results, retrieved by findAll with include statement.
    I have thousands of companies, where each company belongs to many City.
    City belongs to Region, Region belongs to Country.
    I need to get the last 10 companies for specific Country.

    The code is following:

    Country.prototype.getCompanies = function(options={}){
        const include = [{
          model: conn.models.city,
          required: true,
          duplicating: false,
          include: [{
            model: conn.models.region,
            required: true,
            duplicating: false,
            include: [{
              model: conn.models.country,
              where: {
                id: this.get('id')
              }
            }]
          }]
        }];
    
        return conn.models.company.findAll({
          where: options.where,
          limit: options.first,
          include: include,
          order: options.order ? [options.order.split(' ')] : undefined
        });
      };

    It generates following SQL

    SELECT
        "company"."id",
        "company"."name",
        "company"."corporateForm",
        "company"."description",
        "company"."headCompanyId",
        "company"."headOfficeCityId",
        "company"."departments",
        "company"."stockTemperatures",
        "company"."phones",
        "company"."contactPerson",
        "company"."inn",
        "company"."ogrn",
        "company"."address",
        "company"."emails",
        "company"."websites",
        "company"."youtubeVideos",
        "company"."vk",
        "company"."facebook",
        "company"."twitter",
        "company"."instagram",
        "company"."addedUserId",
        "company"."deletedAt",
        "company"."createdAt",
        "company"."updatedAt",
        "cities"."id" AS "cities.id",
        "cities"."name" AS "cities.name",
        "cities"."crt_date" AS "cities.crt_date",
        "cities"."companiesCount" AS "cities.companiesCount",
        "cities"."retailsCount" AS "cities.retailsCount",
        "cities"."region_id" AS "cities.region_id",
        "cities->companyCity"."companyId" AS "cities.companyCity.companyId",
        "cities->companyCity"."cityId" AS "cities.companyCity.cityId",
        "cities->companyCity"."createdAt" AS "cities.companyCity.createdAt",
        "cities->companyCity"."updatedAt" AS "cities.companyCity.updatedAt",
        "cities->region"."id" AS "cities.region.id",
        "cities->region"."name" AS "cities.region.name",
        "cities->region"."crt_date" AS "cities.region.crt_date",
        "cities->region"."country_id" AS "cities.region.country_id",
        "cities->region->country"."id" AS "cities.region.country.id",
        "cities->region->country"."name" AS "cities.region.country.name",
        "cities->region->country"."crt_date" AS "cities.region.country.crt_date"
    FROM
        "companies" AS "company"
        LEFT OUTER JOIN ("companyCities" AS "cities->companyCity"
        INNER JOIN "city" AS "cities" ON "cities"."id" = "cities->companyCity"."cityId")
        ON "company"."id" = "cities->companyCity"."companyId"
        LEFT OUTER JOIN ("region" AS "cities->region"
        INNER JOIN "country" AS "cities->region->country" ON "cities->region"."country_id" = "cities->region->country"."id"
            AND "cities->region->country"."id" = '0')
        ON "cities"."region_id" = "cities->region"."id"
    ORDER BY
        "company"."createdAt" DESC
    LIMIT 10;

    When a company is associated with 3 cities, I will get 7 companies in query result, instead of 10, because company in question will be duplicated 3 times.

    The problem is that I cannot just take a little greater LIMIT value "in advance", because company can be associated with 100+ cities (getting 100 duplicates in result).

    LIMIT will work, when in the SQL-query above I will rewrite SELECT statement to output only columns of company table and use DISTINCT keyword:

    SELECT distinct
        "company"."id",
        "company"."name",
        "company"."corporateForm",
        "company"."description",
        "company"."headCompanyId",
        "company"."headOfficeCityId",
        "company"."departments",
        "company"."stockTemperatures",
        "company"."phones",
        "company"."contactPerson",
        "company"."inn",
        "company"."ogrn",
        "company"."address",
        "company"."emails",
        "company"."websites",
        "company"."youtubeVideos",
        "company"."vk",
        "company"."facebook",
        "company"."twitter",
        "company"."instagram",
        "company"."addedUserId",
        "company"."deletedAt",
        "company"."createdAt",
        "company"."updatedAt"
    FROM
        "companies" AS "company"
        LEFT OUTER JOIN ("companyCities" AS "cities->companyCity"
        INNER JOIN "city" AS "cities" ON "cities"."id" = "cities->companyCity"."cityId")
        ON "company"."id" = "cities->companyCity"."companyId"
        LEFT OUTER JOIN ("region" AS "cities->region"
        INNER JOIN "country" AS "cities->region->country" ON "cities->region"."country_id" = "cities->region->country"."id"
            AND "cities->region->country"."id" = '0')
        ON "cities"."region_id" = "cities->region"."id"
    ORDER BY
        "company"."createdAt" DESC
    LIMIT 10;

    How can I omit the output of associated tables colums in top-level SELECT-query?

  18. AntonAL commented on Apr 10, 2018

    @AntonAL

    Figured out, how to get rid of "cities", "cities->region", "cities->region->country" columns.

    Country.prototype.getCompanies = function(options={}){
        const include = [{
          model: conn.models.city,
          required: true,
          duplicating: false,
          attributes: [], // omits unnecessary columns of associated tables
          include: [{
            model: conn.models.region,
            required: true,
            duplicating: false,
            attributes: [], // omits unnecessary columns of associated tables
            include: [{
              model: conn.models.country,
              attributes: [], // omits unnecessary columns of associated tables
              where: {
                id: this.get('id')
              }
            }]
          }]
        }];
    
        return conn.models.company.findAll({
          where: options.where,
          limit: options.first,
          include: include,
          order: options.order ? [options.order.split(' ')] : undefined
        });
      };

    Resulting SQL is now following:

    SELECT
        "company"."id",
        "company"."name",
        "company"."corporateForm",
        "company"."description",
        "company"."headCompanyId",
        "company"."headOfficeCityId",
        "company"."departments",
        "company"."stockTemperatures",
        "company"."phones",
        "company"."contactPerson",
        "company"."inn",
        "company"."ogrn",
        "company"."address",
        "company"."emails",
        "company"."websites",
        "company"."youtubeVideos",
        "company"."vk",
        "company"."facebook",
        "company"."twitter",
        "company"."instagram",
        "company"."addedUserId",
        "company"."deletedAt",
        "company"."createdAt",
        "company"."updatedAt",
        "cities->companyCity"."companyId" AS "cities.companyCity.companyId",
        "cities->companyCity"."cityId" AS "cities.companyCity.cityId",
        "cities->companyCity"."createdAt" AS "cities.companyCity.createdAt",
        "cities->companyCity"."updatedAt" AS "cities.companyCity.updatedAt"
    FROM
        "companies" AS "company"
        INNER JOIN ("companyCities" AS "cities->companyCity"
            INNER JOIN "city" AS "cities" ON "cities"."id" = "cities->companyCity"."cityId")
            ON "company"."id" = "cities->companyCity"."companyId"
        INNER JOIN "region" AS "cities->region" ON "cities"."region_id" = "cities->region"."id"
        INNER JOIN "country" AS "cities->region->country" ON "cities->region"."country_id" = "cities->region->country"."id"
            AND "cities->region->country"."id" = '0'
        ORDER BY
            "company"."createdAt" DESC
    LIMIT 10;

    Now looking, how to:

    1. omit "cities->companyCity" columns…;
    2. make to use DISTINCT statement.

    Any ideas?

  19. AntonAL commented on Apr 10, 2018

    @AntonAL

    It's strange, but If I rewrite Sequelize query, including intermediate join table, like this:

    Country.prototype.getCompanies = function(options={}){
        const include = [{
          model: conn.models.companyCity, // << explicitly include join-table
          required: true,
          duplicating: false,
          attributes: [],
          include: [{
            model: conn.models.city,
            required: true,
            duplicating: false,
            attributes: [],
            include: [{
              model: conn.models.region,
              required: true,
              duplicating: false,
              attributes: [],
              include: [{
                model: conn.models.country,
                attributes: [],
                where: {
                  id: this.get('id')
                }
              }]
            }]
          }]
        }];

    The part is still present in SELECT statement of SQL-query:

    "cities->companyCity"."companyId" AS "cities.companyCity.companyId",
    "cities->companyCity"."cityId" AS "cities.companyCity.cityId",
    "cities->companyCity"."createdAt" AS "cities.companyCity.createdAt",
    "cities->companyCity"."updatedAt" AS "cities.companyCity.updatedAt"
  20. AntonAL commented on Apr 10, 2018

    @AntonAL

    Also, an advice, described here #3664 (comment), does't work:

    Country.prototype.getCompanies = function(options={}){
        const include = [{
          model: conn.models.city,
          required: true,
          duplicating: false,
          attributes: [],
          through: { // << not working :(, part `"cities->companyCity"` is still present
            attributes: []
          },
          include: [{
            model: conn.models.region,
            required: true,
            duplicating: false,
            attributes: [],
            include: [{
              model: conn.models.country,
              attributes: [],
              where: {
                id: this.get('id')
              }
            }]
          }]
        }];
    
        return conn.models.company.findAll({
          where: options.where,
          attributes: ['id', 'name'],
          limit: options.first,
          include: include,
          order: options.order ? [options.order.split(' ')] : undefined
        });
      };
  21. rivers-dash commented on Nov 7, 2018

    @rivers-dash

    Hello, I think it's working if u put the order properties in an array
    order : [ ['article.created_at', 'DESC'], ],

  22. mi-mazouz commented on Nov 8, 2018

    @mi-mazouz

    any updates?

  23. jacobbodkin commented on Jun 20, 2019

    @jacobbodkin

    Not the best solution, but following @AntonAL 's logic, you can add:

    if (options.distinct) { query = query.replace('SELECT', 'SELECT distinct') }

    to the node_module at sequelize/lib/dialects/abstract/query-generator.js line 1366.

    This allows you to add distinct: true to your findAll.

    I have tested this with Postgres and it seems to be working great. Thank you @AntonAL for finding that distinct works. This would be a great PR if anyone has the time to test it out.

  24. added
    hard
    status: in discussion
    on Oct 11, 2019
  25. added theissue type on Mar 9, 2025
  26. removed
    type: feature
    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

    hardstatus: in discussion

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions