Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
FlandiaYingman opened this issue Apr 30, 2022 · 1 comment
Open

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

FlandiaYingman opened this issue Apr 30, 2022 · 1 comment

Comments

@FlandiaYingman
Copy link

FlandiaYingman commented Apr 30, 2022

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?

Copy link

github-actions bot commented Nov 7, 2024

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.

@github-actions github-actions bot added the stale label Nov 7, 2024
@j2gg0s j2gg0s removed the stale label Jan 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants