2017-04-01 11 views
0

ここにはmany_to_manyの関連付けの質問があります。私は取得していますエラーがpostgresのではEctoの `many_to_many`関連の外部キー名

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) 

を実行するに

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 

で、結合テーブルは

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はを探すの代わりにqbinder_idqbinder_idに設定するにはどうすればよいですか?

+1

。あなたは 'join_keys'キーワード引数でアソシエーションを自分自身で設定することができます。この[doc](https://hexdocs.pm/ecto/Ecto.Schema.html#many_to_many/3-options) –

+0

Spot onをチェックしてください。ありがとう。あなたが答えを加えたら、私はそれを受け入れます。 –

+0

喜んで助けてください!乾杯! –

答えて

1

これはoptionsの引数Ecto.Schema.many_to_many/3によって簡単にカスタマイズできます。

列名はオプションjoin_keysで構成することができ、そして同じように使用する必要があります:私はあなたのモデル名が `Qbinders`あり、そのように、列名は、その名前から派生しているので、それはだ疑い

many_to_many :qbooks, Project.Qbooks, join_through: "qbook2qbinder", 
             join_keys: [{qbook_id: :id, qbinder_id: :id}] 
関連する問題