Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to Many relationship in Ecto

I have a Users model and a Chats model. Intuitively multiple people will belong to the same chat group at any time and each person can have many chat groups. Therefore the chat group must belong to multiple user_id's.

My schema for the chat group and users are:

schema "chatGroups" do     field :name, :string     has_many :messages, Message     belongs_to :user, User      timestamps end  schema "users" do     field :name, :string     has_many :chatGroups, ChatGroup      timestamps end 

Any suggestions how to handle this?

like image 223
Terence Chow Avatar asked Oct 02 '15 03:10

Terence Chow


2 Answers

This is an old question and the previously accepted answer was no longer the de facto way.

Ecto now supports HABTM or many to many associations.

https://hexdocs.pm/ecto/Ecto.Schema.html#many_to_many/3

many_to_many :users, MyApp.User, join_through: "chat_group_users" 
like image 95
kgpdeveloper Avatar answered Sep 25 '22 12:09

kgpdeveloper


Ecto has support for has_many/3 through relationships. This involves creating an intermediate table between your chat groups and your users.

You can do this with the following schema:

chat_group.ex:

schema "chat_groups" do   has_many :chat_group_users, MyApp.ChatGroupUser   has_many :users, through: [:chat_group_users, :user] end 

chat_group_user.ex:

schema "chat_group_users" do   belongs_to :chat_group, MyApp.ChatGroup   belongs_to :user, MyApp.User end 

You can also do the association the other way:

user.ex:

schema "users" do   has_many :chat_group_users, MyApp.ChatGroupUsers   has_many :chats, through: [:chat_group_users, :chat] end 

This allows you to do things like:

Repo.get(Chat, 1) |> Repo.preload(:users) 

This will fetch the users for your chat model and populate the :user key with the value.

like image 33
Gazler Avatar answered Sep 23 '22 12:09

Gazler