查询记录上的 ID - Phoenix 和 Elixir

Query for an ID on a record - Phoenix and Elixir

我来自 rails 背景(就像许多 Elixir 人一样)。我当前的问题是我正在尝试查询特定记录。这对我来说在 rails 中很简单,但我似乎无法在 Phoenix 中弄明白。这是我正在尝试做的事情:

我有一个 Location table has_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,我不确定它在做什么。谁能帮我解决这个问题?

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

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

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

获取该记录