【问题标题】:Get primary key from query in Ecto从 Ecto 中的查询中获取主键
【发布时间】:2018-03-01 08:42:05
【问题描述】:

我想从查询中动态获取主键。我有一个想法。首先,我从查询中获取模式(我不知道,如何)。之后,我从模式中获取表名:

{_, table_name} = %Core.Schema{}.__meta__.source

并发送 SQL,它将获得主键。 于是,就产生了三个问题:

  1. 有没有办法从查询中获取架构(以及在获取表名之后)

  2. 直接从查询中获取表名?

  3. Ecto.primary_key() 不适用于查询,也许他们有其他方法?

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    如果查询是使用架构模块(即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]
    

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多