Repo.all 失败,因为我有自定义主键

Repo.all fails because I have a custom primary key

我为没有 id 字段的 table 生成并 运行 迁移(使用字段 league_id 作为主键)。我确认迁移按预期工作(检查了 psql 中的数据库并且 table 确实没有 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 * 类型的查询?)

如果您使用与 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 对此进行了详细解释。

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

@primary_key {:personid, :id, autogenerate: true}

schema "people" do
    field :id, :integer, [source: :personid]
    ...
    many_to_many :...
end