SeaQL / SeaQL/sea-orm

`find_with_related` implicitly adds ordering on `left.id`

Open
#2,220 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Area:docs Category:enhancement
Dominant language
Rust
Stars
9.9k
Forks
734
Avg merge
6h 36m
Merged PRs (30d)
8

Description

Description

find_with_related implicitly adds an order by on the left table's id. This is extremely unintuitive; for instance:

LeftEntity::find()
  .find_with_related(RightEntity)
  .filter(...)
  .order_by(LeftCol1, Order::Desc)
  .order_by(LeftCol2, Order::Desc)

generates a query that is ordered by (LeftId, LeftCol1, LeftCol2) rather than (LeftCol1, LeftCol2), as might be expected.

Steps to Reproduce

  1. Write a query using find_with_related that includes an order_by after the find_with_related
  2. Either try to execute it, or .build(..).to_string() it
  3. Observe that the order clause has order by left.id asc prepended to it
Expected Behavior

In the example case from the description, I would expect the ordering to be (LeftCol1, LeftCol2).

Actual Behavior

In the example case from the description, the actual ordering is (LeftId, LeftCol1, LeftCol2).

Reproduces How Often

Deterministically.

Workarounds

Placing the order_by before the find_with_related, like so:

LeftEntity::find()
  .order_by(LeftCol1, Order::Desc)
  .order_by(LeftCol2, Order::Desc)
  .find_with_related(RightEntity)
  .filter(...)

produces an ordering on (LeftCol1, LeftCol2, LeftId), which is acceptable. However, the fact that the query needs to be constructed in this manner is very non-obvious.

Reproducible Example

See description

Versions

├── sea-orm v0.12.15 (*)
├── sea-query v0.30.7 (*)
│   ├── sea-orm v0.12.15 (*)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the Rust query shown with find_with_related, order_by, and build().to_string(), then inspect the SeaORM code path for find_with_related ordering. Done means ordering added after find_with_related no longer places left.id before the requested columns, while the documented workaround behavior remains covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.