基于外关联查询

Ecto association query based

在 Rails 控制器中,您经常会看到下面的代码,以便仅获取属于 current_user;

的帖子
class PostsController < APIController
  def show
    current_user.posts.find(params[:id])
  end
end

用 Ecto 表达这一点的最佳方式是什么?

您可以将 Ecto.Model.assoc/2 与 Repo 函数一起使用。

获取单品:

assoc(current_user, :posts) |> Repo.get(id)

获取用户的所有帖子:

assoc(current_user, :posts) |> Repo.all()

您也可以使用它来编写查询:

例如

defmodule Post do
  use Ecto.Model

  ...

  def published(query) do
    from p in query,
      where: p.published
  end
end

assoc(current_user, :posts) |> Post.published() |> Repo.all()