【问题标题】:Repo.all fails because I have a custom primary keyRepo.all 失败,因为我有一个自定义主键
【发布时间】:2018-12-22 17:53:07
【问题描述】:

我为没有id 字段的表生成并运行迁移(使用字段league_id 作为主键)。我确认迁移按预期进行(检查了 psql 中的数据库,该表确实没有 id 字段,league_id 是主键)。

当我运行Repo.all(League) 时出现以下错误:

13:01:14.962 [debug] QUERY ERROR source="leagues" db=2.8ms

SELECT l0."id", l0."league_id" FROM "leagues" AS l0 []

** (Postgrex.Error) ERROR 42703 (undefined_column): column l0.id does not exist

有没有办法告诉 Repo.all/1 没有 id 字段(除了手动构建 SELECT * 类型的查询?)

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

    如果您使用与id 不同的主键列,则可以在声明架构时指定使用@primary_key 属性:

    # See documentation link below for what values the options list accepts.
    @primary_key {:league_id, :id, []} 
    schema "leagues" do
      ...
    end
    

    或者如果您不想在查询中使用该列,可以将键设置为false:

    @primary_key false
    schema "leagues" do
      ...
    end
    

    The documentation 详细解释了这一点。

    【讨论】:

    • 谢谢!对于未来的读者,请注意我必须在元组中添加一个空列表以避免编译错误(它需要 false 或 { name, type, opts },并且当您以这种方式定义主键时,您不会也包含该字段在schema 通话中。
    • 谢谢,我已经修复了包含选项列表的答案!
    【解决方案2】:

    仅供参考:当存在 many_to_many 关系时,我还必须覆盖模式块中的字段。

    @primary_key {:personid, :id, autogenerate: true}
    
    schema "people" do
        field :id, :integer, [source: :personid]
        ...
        many_to_many :...
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-17
      • 2016-10-29
      • 2020-06-01
      • 1970-01-01
      • 2012-07-09
      • 2017-08-10
      • 2012-02-21
      • 2017-07-31
      相关资源
      最近更新 更多