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

Are there any suggestions for one to many queries? #1117

Open
sarvesh-deserve opened this issue Oct 24, 2024 · 2 comments
Open

Are there any suggestions for one to many queries? #1117

sarvesh-deserve opened this issue Oct 24, 2024 · 2 comments

Comments

@sarvesh-deserve
Copy link

Are there any suggestions for one to many queries?

@dantownsend
Copy link
Member

Something like this?

class Manager(Table):
    name = Varchar()

class Band(Table):
     manager = ForeignKey(Manager)
     name = Varchar()

So a manager has several bands.

Are you trying to query all bands for a manager? You can do something like:

from piccolo.query.methods.select import SelectRaw

await Manager.select(Manager.name, SelectRaw("ARRAY(SELECT name FROM band where manager = manager.id) AS band_names"))

@sinisaos
Copy link
Member

I didn't get it at first, but it's basically a reverse lokoop. We have PR for that. @dantownsend solution is great for Postgres, but for SQlite (ARRAY is not supported) you can use a less efficient solution like this one (work both sync and async)

managers = Manager.select().run_sync()
bands = Band.select().run_sync()
# Maps manager_id to a list of bands
bands_map = {i[0]: list(i[1]) for i in it.groupby(bands, lambda x: x["manager"])}
rows = []
for manager in managers:
    rows.append(
        {
            "manager": manager["name"],
            "bands": [i["name"] for i in bands_map[manager["id"]]],
        }
    )
print(rows)

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

3 participants