Elixir 基于外显关联查询
在Rails控制器中,您经常看到下面的代码,以便只获取属于当前用户的帖子Elixir 基于外显关联查询,elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,在Rails控制器中,您经常看到下面的代码,以便只获取属于当前用户的帖子 class PostsController < APIController def show current_user.posts.find(params[:id]) end end class PostsController
class PostsController < APIController
def show
current_user.posts.find(params[:id])
end
end
class PostsController
用EXTO表达这一点的最佳方式是什么?您可以与Repo函数一起使用
要获取单个项目,请执行以下操作:
assoc(current_user, :posts) |> Repo.get(id)
要为用户获取所有帖子的链接,请执行以下操作:
assoc(current_user, :posts) |> Repo.all()
您还可以使用它来组合查询:
e、 g
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()