从 Ecto 中的查询中获取主键
Get primary key from query in Ecto
我想从查询中动态获取主键。我有一个想法。首先,我从查询中获取模式(我不知道如何)。之后,我从架构中得到 table 名称:
{_, table_name} = %Core.Schema{}.__meta__.source
并发送 SQL,这将获得主键。
于是,三个问题诞生了:
有没有办法从查询中获取模式(并在获取 table 名称之后)
直接从查询中获取table姓名?
Ecto.primary_key() 不适用于查询,也许他们有其他方法?
如果查询是使用模式模块构建的(即 from(p in Post)
,而不是 from(p in "posts")
),您可以使用查询的 from
字段取回模块:
iex(1)> query = from(p in Post, where: p.id == 1)
#Ecto.Query<from p in MyApp.Post, where: p.id == 1>
iex(2)> %{from: {_table, module}} = query
#Ecto.Query<from p in MyApp.Post, where: p.id == 1>
iex(3)> module
MyApp.Post
要获取模块架构中定义的主键,您可以在模块上调用 .__schema__(:primary_key)
:
iex(4)> module.__schema__(:primary_key)
[:id]
我想从查询中动态获取主键。我有一个想法。首先,我从查询中获取模式(我不知道如何)。之后,我从架构中得到 table 名称:
{_, table_name} = %Core.Schema{}.__meta__.source
并发送 SQL,这将获得主键。 于是,三个问题诞生了:
有没有办法从查询中获取模式(并在获取 table 名称之后)
直接从查询中获取table姓名?
Ecto.primary_key() 不适用于查询,也许他们有其他方法?
如果查询是使用模式模块构建的(即 from(p in Post)
,而不是 from(p in "posts")
),您可以使用查询的 from
字段取回模块:
iex(1)> query = from(p in Post, where: p.id == 1)
#Ecto.Query<from p in MyApp.Post, where: p.id == 1>
iex(2)> %{from: {_table, module}} = query
#Ecto.Query<from p in MyApp.Post, where: p.id == 1>
iex(3)> module
MyApp.Post
要获取模块架构中定义的主键,您可以在模块上调用 .__schema__(:primary_key)
:
iex(4)> module.__schema__(:primary_key)
[:id]