Search code examples
many-to-manypivotelixirecto

Elixir Ecto: Using a Pivot Attribute in a Many To Many Relationship


I am currently having troubles figuring out how to use pivot attributes in an Ecto many-to-many relationship.

I found the following question but unfortunately nobody had an answer: https://stackoverflow.com/questions/37158184/elixir-ecto-pivot-many-to-many-table-attributes

Basically I need the same setup as mentioned in the question. Two models and I need to store data to the pivot entry.

Has anybody a solution for this problem?

Thanks in advance!


Solution

  • I am doing something like the following in one of my applications

    def Foo do
      schema "foos" do
        field :name, :string
    
        has_many :bars_foos
      end
    end
    
    def Bar do
      schema "bars" do
        field :other, :integer
    
        has_many :bars_foos
      end
    end
    
    def BarFoo do
      schema "bars_foos" do
        field :size, :integer
    
        belongs_to :bars
        belongs_to :foos
      end
    end
    

    This uses has_many and belongs_to instead of many_to_many, but it accomplishes something very similar. You can also still use the many_to_many with through if you need a direct link to the other dataset.