Elixir 如何通过特定查询获取“has_many”
我有一个与Elixir 如何通过特定查询获取“has_many”,elixir,ecto,Elixir,Ecto,我有一个与有很多关联的异位模型。我想在默认情况下用一些查询定义这个关联 像 我想获取未被删除的注释(已删除是MyApp.Comment架构的布尔字段,应等于false)。实现这一目标的途径是什么 我的尝试#1 我试着去做 has_many :comments, Ecto.Query.from(c in MyApp.Comment, where: v.deleted == false) 但是我有 (ArgumentError) association queryable must be a sc
有很多关联的异位模型。我想在默认情况下用一些查询定义这个关联
像
我想获取未被删除的注释(已删除是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
如果您有Post
和Comment
模型,您可以在exto.Query
和exto.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)
我知道,谢谢。但是如何在模式块中指定这种关联呢?这就是问题所在哦!通常,我在模型中创建一个方法,然后在控制器操作中使用它。这是明确和易于编写。这会很有趣,但我从未见过有人做过这样的事情。我认为这是不可能的。Ecto不像活动记录那样有作用域的概念。我能建议的最接近的事情是在user.ex
中创建一个函数,沿着active\u 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)