Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load an association without preloading it?

Tags:

elixir

ecto

I have the following two models:

schema "users" do
    field :email, :string
    field :crypted_password, :string
    field :password, :string, virtual: true

    has_many :exercise_entries, ExerciseEntry

    timestamps
end

and:

schema "exercise_entries" do
  field :date, Ecto.DateTime
  field :exercise, :string
  field :category, :string
  field :weight, :float
  field :reps, :integer
  belongs_to :user, User

  timestamps
end

I ran the following code in iex:

u = Repo.get(User, 1)
iex(8)> u.exercise_entries
#Ecto.Association.NotLoaded<association :exercise_entries is not loaded>

I know I can do Repo.get(User,1) |> Repo.preload([:exercise_entries]) and then I can access the exercise_entries. Is it possible though to somehow load the exercise_entries without preloading them first?

like image 404
Geo Avatar asked Jan 18 '16 21:01

Geo


1 Answers

Ecto needs to perform another database query to fetch exercise entries. It will be normal Repo.all query, but instead of building it manually, you can use Ecto.assoc

ee = Repo.all(Ecto.assoc(u, :exercise_entries))
like image 121
tkowal Avatar answered Nov 03 '22 20:11

tkowal