简体   繁体   English

查询记录上的ID-Phoenix和Elixir

[英]Query for an ID on a record - Phoenix and Elixir

I'm coming from a rails background (like many Elixir folks). 我来自Rails背景(就像许多Elixir一样)。 My current problem is that I'm trying to query for a particular record. 我当前的问题是我正在尝试查询特定记录。 This is a no brainer in rails for me but I can't seem to figure it out in Phoenix. 对我而言,这毫无疑问,但我似乎无法在Phoenix中弄清楚。 Here is what I'm trying to do: 这是我想要做的:

I have a Location table that has_many Monitors and a Monitor has a number that is not an ID. 我有一个has_many MonitorsLocation表,并且Monitor的编号不是ID。 These number are only unique to a Location so I can't simply find particular monitor with just the monitor number. 这些编号仅对于位置而言是唯一的,因此我不能仅凭监视器编号简单地找到特定的监视器。 So I have to scope it to the Location it belongs to. 因此,我必须将其范围限定为它所属的位置。 In Rails I would do something like this: 在Rails中,我将执行以下操作:

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

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

Easy peasy with Rails active record but How can I do this with Phoenix? 轻松记录Rails活跃记录,但是如何使用Phoenix做到这一点? Here is my current attempt that is not working as I expect. 这是我当前的尝试,没有按我的预期工作。

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)

That is pulling up the wrong ID and I'm not sure what its doing. 那是拉错了ID,我不确定它在做什么。 Can anyone tell help me out with this? 谁能告诉我这个吗?

The most straightforward conversion of that Rails code would be this: 该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 a query that's basically from m in Monitor, where: m.location_id == ^location.id . Ecto.assoc(location, :monitors)返回一个基本上from m in Monitor, where: m.location_id == ^location.id的查询from m in Monitor, where: m.location_id == ^location.id We then add more constraints to it ( where: m.number == ^params["monitor"] ) and fetch that record using Repo.get_by . 然后,我们对其添加更多约束( where: m.number == ^params["monitor"] ),并使用Repo.get_by获取该记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM