Skip to content

Incorrect order when eager-loading hasMany association #1412

Closed

Description

@sebastianhoitz

I have three models:

  • Order
  • Customer
  • OrderItems

I query them like this:

options =
  limit: 100
  order: [
    ['orders.id', 'DESC']
  ]
  include: [
    {model: App.Customer, as: "Customer"},
    {model: App.OrderItem, as: "OrderItems"}
  ]

App.Order.findAll(options).success (data) =>
  for elm in data
    console.log elm.id

the resulting SQL query looks like this:

Executing (default): SELECT "orders".*, "Customer"."id" AS "Customer.id", [...] "OrderItems"."updatedAt" AS "OrderItems.updatedAt" FROM (SELECT "orders".* FROM "orders" **ORDER BY "orders"."id" DESC** LIMIT 100) AS "orders" LEFT OUTER JOIN "customers" AS "Customer" ON "Customer"."id" = "orders"."customerId" LEFT OUTER JOIN "orderitems" AS "OrderItems" ON "orders"."id" = "OrderItems"."orderId";

and the output is something like this (notice this should be sorted by ID!):

1
2
5
4
3

I marked the wrong part in the SQL query in bold. That ORDER BY statement should be located at the very end of the query to make sure, that the resulting joined rows are in the correct order.

Also note: When removing the OrderItems for eager-loading the order is correct.

Activity

  1. mickhansen commented on Feb 19, 2014

    @mickhansen
    Contributor

    Actually the ORDER BY should be on both the inner and outer query should it not?
    This should be a decently simple fix, i'll look at it tommorow - Just need to add subQueryOrder's to the mainQueryOrder, building on my commit earlier today: 204c7e7

  2. self-assigned this
    on Feb 19, 2014
  3. sebastianhoitz commented on Feb 19, 2014

    @sebastianhoitz
    ContributorAuthor

    Yes, you are right. It should be on both queries.

    That sounds very good! Thank you for the quick response! 👍

  4. mickhansen commented on Feb 19, 2014

    @mickhansen
    Contributor

    I did a dirty commit: 5f5eb36 - Could you test against master and see if it fixes your case?

  5. sebastianhoitz commented on Feb 19, 2014

    @sebastianhoitz
    ContributorAuthor

    Yes, I can confirm that this fixes the issue for me. Very nice! :)

  6. mickhansen commented on Feb 20, 2014

    @mickhansen
    Contributor

    Great :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions