Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 基于外显关联查询_Elixir_Phoenix Framework_Ecto - Fatal编程技术网

Elixir 基于外显关联查询

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

在Rails控制器中,您经常看到下面的代码,以便只获取属于当前用户的帖子

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()