【问题标题】:Ecto association query based基于 Ecto 关联查询
【发布时间】:2015-10-23 19:18:02
【问题描述】:

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

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

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

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    您可以将Ecto.Model.assoc/2 与回购功能一起使用。

    获取单个项目:

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

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多