有人用复合主键成功创建到表的关系吗? 我正在努力实现以下目标:
create table(:resources, primary_key: false) do
add :id, :uuid, primary_key: true
add :version, :id, primary_key: true
# ... other details about the resource
end
create table (:resource_instances, primary_key: false) do
add :id, :uuid, primary_key: true
add :resource_id,
references(:resources, type: :uuid, column: :id),
null: false
add :resource_version,
references(:resources, type: :id, column: :version),
null: false
# ... specific details about this instance of the resource
end
运行迁移会生成以下日志:
11:24:00.100 [info] create table my_schema.resources
11:24:00.152 [info] create table my_schema.resource_instances
** (Postgrex.Error) ERROR 42830 (invalid_foreign_key) there is no unique constraint matching given keys for referenced table "resources"
(ecto_sql) lib/ecto/adapters/sql.ex:629: Ecto.Adapters.SQL.raise_sql_call_error/1
(elixir) lib/enum.ex:1336: Enum."-map/2-lists^map/1-0-"/2
(ecto_sql) lib/ecto/adapters/sql.ex:716: Ecto.Adapters.SQL.execute_ddl/4
(ecto_sql) lib/ecto/migration/runner.ex:343: Ecto.Migration.Runner.log_and_execute_ddl/3
(ecto_sql) lib/ecto/migration/runner.ex:117: anonymous fn/6 in Ecto.Migration.Runner.flush/0
(elixir) lib/enum.ex:1948: Enum."-reduce/3-lists^foldl/2-0-"/3
(ecto_sql) lib/ecto/migration/runner.ex:116: Ecto.Migration.Runner.flush/0
(stdlib) timer.erl:166: :timer.tc/1
(ecto_sql) lib/ecto/migration/runner.ex:25: Ecto.Migration.Runner.run/7
(ecto_sql) lib/ecto/migrator.ex:342: Ecto.Migrator.attempt/7
(ecto_sql) lib/ecto/migrator.ex:243: anonymous fn/4 in Ecto.Migrator.do_up/4
(ecto_sql) lib/ecto/migrator.ex:324: anonymous fn/3 in Ecto.Migrator.run_maybe_in_transaction/6
(ecto_sql) lib/ecto/adapters/sql.ex:898: anonymous fn/3 in Ecto.Adapters.SQL.checkout_or_transaction/4
(db_connection) lib/db_connection.ex:1415: DBConnection.run_transaction/4
(ecto_sql) lib/ecto/migrator.ex:323: Ecto.Migrator.run_maybe_in_transaction/6
(elixir) lib/task/supervised.ex:90: Task.Supervised.invoke_mfa/2
(elixir) lib/task/supervised.ex:35: Task.Supervised.reply/5
(stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
答案 0 :(得分:1)
尝试一下:
create table(:resources, primary_key: false) do
add :id, :uuid, primary_key: true
add :version, :id, primary_key: true, auto_generate: true
end
create unique_index(:resources, [:id])
create unique_index(:resources, [:version])
create table(:resource_instances, primary_key: false) do
add :resource_id,
references(:resources, type: :uuid, column: :id),
null: false
add :resource_version,
references(:resources, type: :id, column: :version),
null: false
end
由于创建复合键,您似乎还需要创建单独的唯一索引才能引用那些 因此基本上为各个列添加了unique_indices