【问题标题】:Ecto - how to get `has_many` with specific queryEcto - 如何通过特定查询获取“has_many”
【发布时间】:2016-09-21 16:00:20
【问题描述】:

我有一个带有 has_many 关联的 ecto 模型。我想在默认情况下用一些查询来定义这个关联。

喜欢

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

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

我想获取不是 deleted 的 cmets(删除的是 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

【问题讨论】:

  • 我认为这是不可能的。 Ecto 没有像活动记录那样的范围概念。我可以建议的最接近的方法是在user.ex 中按照active_comments 的行创建一个函数。

标签: elixir ecto


【解决方案1】:

如果你有PostComment两个模型,你可以通过Ecto.Query然后Ecto.Repo找到未删除的cmets。

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)

【讨论】:

  • 我知道,谢谢。但是如何在模式块中指定这种关联呢?这就是问题
  • 哦!通常我在模型中创建一个方法,然后在控制器操作中使用它。这是清晰且易于撰写的。这会很有趣,但我从未见过有人做过这样的事情。
猜你喜欢
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多