【问题标题】:Query for an ID on a record - Phoenix and Elixir查询记录上的 ID - Phoenix 和 Elixir
【发布时间】:2017-07-26 22:55:17
【问题描述】:

我来自 Rails 背景(像许多 Elixir 人一样)。我目前的问题是我正在尝试查询特定记录。对我来说,这对我来说毫无疑问,但在凤凰城我似乎无法弄清楚。这是我想要做的:

我有一个 Location 表,其中有_many Monitors 和一个监视器有一个不是 ID 的数字。这些编号仅对某个位置是唯一的,因此我不能仅通过显示器编号简单地找到特定的显示器。因此,我必须将其范围限定为它所属的位置。在 Rails 中,我会这样做:

location = Location.find(params[:location_id])

monitor = location.monitors.find_by(number: params[:monitor_number])

使用 Rails 活动记录很容易,但是如何使用 Phoenix 做到这一点?这是我目前的尝试,但没有按预期工作。

monitor_query = from m in Monitor,
  where: m.location_id == ^upload_params["location_id"],
  where: m.number == ^upload_params["monitor_number"],
  select: m.id

monitor = Repo.all(monitor_query)

这是提取了错误的 ID,我不确定它在做什么。谁能告诉我这个问题?

【问题讨论】:

    标签: ruby-on-rails elixir phoenix-framework ecto


    【解决方案1】:

    Rails 代码最直接的转换是这样的:

    location = Repo.get(Location, params["location_id"])
    monitor = Repo.get_by(Ecto.assoc(location, :monitors), number: params["monitor_number"])
    

    Ecto.assoc(location, :monitors) 返回一个基本上是from m in Monitor, where: m.location_id == ^location.id 的查询。然后我们向它添加更多约束 (where: m.number == ^params["monitor"]) 并使用 Repo.get_by 获取该记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2017-09-25
      • 2018-05-22
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      相关资源
      最近更新 更多