从记录集中获取单条记录

Get a single record from a record set

简单请求:

    a1 = where(MyModel, [x], is_nil(x.some_foreign_id)) |> Repo.one()

异常:

** (exit) an exception was raised:                                
    ** (Ecto.MultipleResultsError) expected at most one result but got 6 in query:

是的,有一些记录,没关系,但我打算拿第一个。为什么会出现异常以及如何解决?

Why the exception

Repo.one 总是 returns nil 或一条记录,如果程序员自己将 limit 添加到查询而不是从数据库中获取更多记录然后再进行查询会更好抛出一个。

how to fix it?

您可以使用 limit(1):

a1 = where(MyModel, [x], is_nil(x.some_foreign_id)) |> limit(1) |> Repo.one()

请注意,如果没有 order,返回的记录在大多数数据库中通常是未定义的。您可以按 id 排序以获得最低 id:

的记录
a1 = where(MyModel, [x], is_nil(x.some_foreign_id)) |> order_by(:id) |> limit(1) |> Repo.one()