queries on Phoenix

about the book

I finished reading “Programming Elixir 1.2”. The concurrency part of the book is really fun though it was a bit hard for me :sweat:

Macro and Protocols are also amazing! They’re for reading rather for writing because seem to be magical and unreadable for others.

Anyway, I don’t understand Elixir completely, and I will read it several times and read more Elixir book like Metaprogramming Elixir.

query in Phoenix

By the way, I fell in Ecto.Query API in Phoenix app a little. Then I leave memo about it.

There’s a relation between User and Post. A user has_many posts.

defmodule MyApp.Post do
  # bluh bluh

  # I don't know whether it's a good way to use `repo`
  # inside model(entity) class(module).
  def get_all_published(repo) do
    query = from p in __MODULE__,
      where: not is_nil(p.published_at),
      order_by: [desc: :inserted_at],
      preload: [:user]
    repo.all(query)
  end

  # or
  def get_all_published(repo) do
    query = from p in __MODULE__,
      where: not is_nil(p.published_at),
      order_by: [desc: :inserted_at]
    repo.all(query) |> repo.preload(:user)
  end
end

What I was confused

I specified module(table) name as string .

This requires select [column names] and not work preloading.

defmodule MyApp.Post do
  # bluh bluh

  def get_all_published(repo) do
    query = from p in "posts", # <- here
      where: not is_nil(p.published_at),
      order_by: [desc: :inserted_at],
      preload: [:user] # <- this not work
    repo.all(query)
  end
end
just use __MODULE__ for query’s from function. (In this case, __MODULE__ means MyApp.Post.)

:sunglasses:

Contents