Preload and select columns

787 views
Skip to first unread message

Vladislav Shcherbin

unread,
Feb 24, 2016, 1:40:39 AM2/24/16
to elixir-ecto
I'm a bit confused and need some help.

I have Universities and each University has a City (one to many).

I need to take 2 Universities. I do:

universities = University
|> limit(2)
|> Repo.all

Since, I don't need Poison to return metadata and need only some fields, I do:

universities = University
|> limit(2)
|> select([u], %{
  title: u.fullTitle
})
|> Repo.all

So, on client I receive this:

[
{
title: "title one"
},
{
title: "title two"
}
]

Now, I need to preload city

If I take the whole data and preload city - it works:

universities = University 
|> preload(:city) 
|> limit(2
|> select([u], u
|> Repo.all

But, I don't know, how to exclude metadata and take only needed columns here. I want to receive on client this:

[
{
title: "title one",
city: {
title: "city one"
}
},
{
title: "title two"
city: {
title: "city two"
}
}
]

I keep rereading the docs and trying various syntax combinations, but I can't handle it.

Can you help me, please?

José Valim

unread,
Feb 24, 2016, 2:46:46 AM2/24/16
to elixi...@googlegroups.com
You can either do it in the query:

    universities =
      from u in University,
        left_join: c in assoc(u, :city),
        limit: 2,
        select: %{title: u.title, city: %{title: c.title}}

Ecto 2.0 will also allow:

    universities =
      from u in University,
        left_join: c in assoc(u, :city),
        limit: 2,
        select: [:title, city: [:title]]

Or you can just use Elixir after the query:

    universities =
      University 
      |> preload(:city) 
      |> limit(2) 
      |> select([u], u) 
      |> Repo.all

    for u <- universities do
      %{title: u.title,
        city: %{title: u.city.title}}
    end

Vladislav Shcherbin

unread,
Feb 24, 2016, 3:03:06 AM2/24/16
to elixir-ecto, jose....@plataformatec.com.br
Oh, I thought we could select fields with preload. So, basically, we need to use joins to do this.

Thank you, the first variants works great.

I'm using 2.0 beta (works great), the second variant is expected in the release version?
Reply all
Reply to author
Forward
0 new messages