Ecto - 如何使用特定查询获取`has_many`

时间:2016-09-21 16:00:21

标签: elixir ecto

我有一个has_many关联的ecto模型。我想默认用一些查询来定义这种关联。

defmodule MyApp.User do
  use MyApp.Web, :model

  schema "users" do
    has_many :comments, MyApp.Comment
  end
end

我想获取不是deleted的注释(删除是MyApp.Comment架构的布尔字段,它应该等于false)。实现这个目标的方法是什么?

我的尝试#1

我试着做

has_many :comments, Ecto.Query.from(c in MyApp.Comment, where: v.deleted == false)

但我得到了

(ArgumentError) association queryable must be a schema or {source, schema}, got: #Ecto.Query

1 个答案:

答案 0 :(得分:0)

如果您拥有PostComment模型,则可以在Ecto.Query然后Ecto.Repo的帮助下找到未删除的评论。

query = from c in Comment,
        where c.deleted == false,
        select: c

comments = MyApp.Repo.all(query) # This will give you all the non-deleted comments

此外,您可能需要在您的应用程序中进行以下查询。

alias MyApp.{Post,Comment}

query = from p in Post,
        join: c in assoc(p, :comments),
        where: c.deleted == false,
        select: {p, c} # for comments only - just select: c.

Blog.Repo.all(query)
相关问题