Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preloading Ecto Associations by default

Tags:

elixir

ecto

Is there any way to preload ecto associations without explicitly using preload:?

Something like an option in the schema?

schema "gadgets" do
  field :foo,
  has_many :bars, Myapp.Bar, preload: true
end

I'm doing something like

Repo.get(Gadget, id)
  |> Repo.preload: [:bars]

Edit: the reason I'm trying to do this is because I want to preload a related model to the already preloaded related model, like

 preload: [:invoices preload: :items] 
like image 647
Dania_es Avatar asked Apr 12 '15 22:04

Dania_es


1 Answers

You can also preload as part of a query:

defmodule Gadget do
  use Ecto.Model

  # ...

  def with_invoices(query) do
    from q in query, preload: [invoices: :items]
  end
end

Then:

Gadget
|> Gadget.with_invoices
|> Repo.get!(id)
like image 99
José Valim Avatar answered Oct 28 '22 21:10

José Valim