Search code examples
elixirecto

Repo.all fails because I have a custom primary key


I generated and ran a migration for a table with no id field (uses the field league_id as a primary key). I confirmed that the migration worked as intended (checked the database in psql and the table indeed has no id field and league_id is the primary key).

When I run Repo.all(League) I get the following error:

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

Is there a way to tell Repo.all/1 that there is no id field (aside from manually building a SELECT * -type query?)


Solution

  • If you use a different primary key column than id, you can specify that using the @primary_key attribute when declaring the schema:

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

    or if you don't want to use that column in queries, you can set the key to false:

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

    The documentation explains this in detail.