2017-04-01 128 views
0

這裏是一個關於many_to_many關聯的問題。我得到的錯誤是Ecto中`many_to_many`關聯的外鍵名稱

INSERT INTO "qbinders" ("title","typecode","inserted_at","updated_at","id") VALUES ($1,$2,$3,$4,$5) ["Math", "Jim1000", {{2017, 4, 1}, {15, 4, 47, 827009}}, {{2017, 4, 1}, {15, 4, 47, 843348}}, <<68, 1 
49, 156, 219, 153, 214, 65, 63, 179, 141, 252, 147, 221, 247, 41, 143>>] 
[debug] QUERY OK db=0.9ms 
commit [] 
** (Postgrex.Error) ERROR 42703 (undefined_column): column q2.qbinders_id does not exist 

運行

qbinder_map = %{ title: "Math", typecode: "Jim1000"} 
changeset = Qbinders.changeset(%Qbinders{}, qbinder_map) 
qbinder = Repo.insert!(changeset) |> Repo.preload(:qbooks) 

qbook_list = 
    %Qbooks{ title: "Algebra1"} 
qbook = Repo.insert!(qbook_list) |> Repo.preload(:qbinders) 

changeset = Ecto.Changeset.change(qbinder) 
      |> Ecto.Changeset.put_assoc(:qbooks, [qbook_list]) 
Repo.update!(changeset) 

Postgres裏,連接表看起來像

CREATE TABLE qbook2qbinder 
(
    qbook_id uuid, 
    qbinder_id uuid, 
    qbook_order integer, 
    inserted_at timestamp without time zone NOT NULL, 
    updated_at timestamp without time zone NOT NULL, 
    CONSTRAINT qbook2qbinder_qbinder_id_fkey FOREIGN KEY (qbinder_id) 
     REFERENCES qbinders (id) MATCH SIMPLE 
     ON UPDATE NO ACTION ON DELETE NO ACTION, 
    CONSTRAINT qbook2qbinder_qbook_id_fkey FOREIGN KEY (qbook_id) 
     REFERENCES qbooks (id) MATCH SIMPLE 
     ON UPDATE NO ACTION ON DELETE NO ACTION 
) 

和模型是

defmodule Project.Qbinders do 
    use Project.Web, :model 

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

    schema "qbinders" do 

     field :title, :string 
     field :reward, :string 

     many_to_many :qbooks, Project.Qbooks, join_through: "qbook2qbinder" 
    timestamps 
    end 

爲什麼Ecto會尋找qbinders_id而不是qbinder_id?我如何將它設置爲qbinder_id

+1

我懷疑這是因爲您的型號名稱爲'Qbinders',正因爲如此,列名是從名稱派生。您應該可以使用'join_keys'關鍵字參數自行配置關聯 - 請檢查此[doc](https://hexdocs.pm/ecto/Ecto.Schema.html#many_to_many/3-選項) –

+0

Spot。謝謝。如果你添加答案,我會接受它。 –

+0

很高興幫助!乾杯! –

回答

1

這可以通過的參數Ecto.Schema.many_to_many/3輕鬆定製。

列名可使用選項join_keys進行配置,並且應該像使用:

many_to_many :qbooks, Project.Qbooks, join_through: "qbook2qbinder", 
             join_keys: [{qbook_id: :id, qbinder_id: :id}]