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

Add :preload option to retrieve and creation functions #21

Open
zoedsoupe opened this issue Jan 28, 2024 · 1 comment
Open

Add :preload option to retrieve and creation functions #21

zoedsoupe opened this issue Jan 28, 2024 · 1 comment

Comments

@zoedsoupe
Copy link
Contributor

Introduction

A cool feature of ecto queries and schemas is to perform cross table join that have associations between them, that way you can retrieve assoc data with simple functions pipelines, as:

def get_user(id) do
  if user = Repo.get(User, id) do
    Repo.preload(user, [:permissions, games: [:owner]])
  end
end

Another option is to define a query to retrieve in a single expression the whole structure:

def get_user(id) do
  q = 
    from u in User,
      where: u.id == ^id,
      preload: [:permissions, games: [:owner]]]
  
  Repo.one(q)
end

Proposal

I’m proposing a new option to swiss_schema functions to apply such preloading assocs on retrieve and creation functions:

defmodule User do
  use Ecto.Schema
  use SwissSchema, repo: MyApp.Repo
  # schema...
end

User.get(id, preload: [:permissions, games: [:owner]])
# %User{id: id, permissions: [], games: [%Game{owner: “foo"}]}
@joeljuca
Copy link
Owner

joeljuca commented May 6, 2024

I'm thinking about the functions that would make sense to receive such opt. I listed below the ones that seem to make sense:

  • get/2, get!/2, get_by/2, get_by!/2, and all/1 (Ecto.Repo Query API)
  • insert/2, insert!/2, insert_or_update/2, insert_or_update!/2 (Ecto.Repo Schema API)
  • create/2 and create!/2 (SwissSchema API)

WDYT?

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