Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.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 如何通过特定查询获取“has_many”_Elixir_Ecto - Fatal编程技术网

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)