Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build and insert a Many to Many association

how to ​build associations​ using between two tables that have a ​_many_to_many_​ relationship using ecto's new many_to_many feature?

I have one to many relationship from organization to user:

organization = Organization.shortcode_changeset(%Organization{}, org_field)
organization = organization |> Repo.insert!
organization |> build_assoc(:users)

which gives

%User{__meta__: #ecto.Schema.Metadata<:built, "users">,......}

user = Repo.preload(user, [:organization, :usergroup])

How can I do this with a many_to_many between users and groups ?

like image 635
user2290820 Avatar asked Jul 15 '16 06:07

user2290820


People also ask

How do you insert a many-to-many relationship?

When you need to establish a many-to-many relationship between two or more tables, the simplest way is to use a Junction Table. A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table.

How do you write a many-to-many relationship in SQL?

Many-to-many (M:M) A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa. To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

What is an example of a many-to-many relationship?

If that sounds abstract, let's look at a specific example: Suppose you have a list of students and a list of classes. There's a many-to-many relationship between the students and their classes, since each student can take multiple classes, and each class can have multiple students enrolled.


2 Answers

Here is how I did it:

user = user |> Repo.preload(:groups)
%Group{} 
|> Group.changeset(@group_field)
|> Repo.insert!
|> Repo.preload(:users)
|> change
|> put_assoc(:users, [user])
|> Repo.update 

I was able to do this only after I found this article which enabled me to proceed: http://blog.roundingpegs.com/an-example-of-many-to-many-associations-in-ecto-and-phoenix/

like image 180
user2290820 Avatar answered Oct 19 '22 19:10

user2290820


Assuming you have some organization name org and a user named user that you want to build an association between you will take the following steps to get create the association in the changeset

changeset = Repo.preload(org, :users) # load the :users for the org
|> Organization.changeset(%{}) # somehow generate a changeset with no changes
|> Ecto.Changeset.put_assoc(:users, [user]) # creates the association

Then all you have left to do is apply the changeset like you normally would. i.e.

Repo.update(changeset)
like image 23
Sam Mercier Avatar answered Oct 19 '22 19:10

Sam Mercier