uptrace / bun

SQL-first Golang ORM
https://bun.uptrace.dev
BSD 2-Clause "Simplified" License
3.78k stars 231 forks source link

How do I quickly sort `has-many` relation? #527

Open FlandiaYingman opened 2 years ago

FlandiaYingman commented 2 years ago

Hi, I am new to bun and Postgres. Assume that I have 100 A models and 1000 B models. Every A model has 10 B models. Now I would like to SELECT all A models (including the B models it has) and sort them in a certain order.

models := new([]AModel)
_ = r.
    NewSelect().
    Model(models).
    Relation("BModel", func(query *bun.SelectQuery) *bun.SelectQuery { return query.Order("sort_id") }). // sorts B model by B.sort_id
    Order("sort_id"). // sorts A model by A.sort_id
    Scan(ctx)

However, when I run this, bundebug shows that bun seems to query all (1000) B models at first, then sorts them together, finally fills them into the A models. This operation is slow, because that a sorting operation has nlogn time complexity, so that sorting 1000 B models is definitely slower than sorting 10 B models 100 times. That is, we don't need to know the order between B models which belong to different A models; we need to only calculate the order between B models which belong to the same A model.

How can I achieve that, or did I write a wrong query to sort them?

github-actions[bot] commented 5 days ago

This issue has been automatically marked as stale because it has not had activity in the last 30 days. If there is no update within the next 7 days, this issue will be closed.