swiss_schema icon indicating copy to clipboard operation
swiss_schema copied to clipboard

Add `:preload` option to retrieve and creation functions

Open zoedsoupe opened this issue 1 year ago • 1 comments

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"}]}

zoedsoupe avatar Jan 28 '24 19:01 zoedsoupe