# Relate three tables (many-to-many)

**URL:** <https://discourse.diesel.rs/t/relate-three-tables-many-to-many/48>\
**Category:** Uncategorized\
**Created:** [September 3, 2018, 1:55pm UTC](https://discourse.diesel.rs/t/relate-three-tables-many-to-many/48 "2018-09-03T13:55:23Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ivan-ochc](https://avatars.discourse-cdn.com/v4/letter/i/919ad9/32.png) [@ivan-ochc](https://discourse.diesel.rs/u/ivan-ochc)\
**Post date:** [September 3, 2018, 1:55pm UTC](https://discourse.diesel.rs/t/relate-three-tables-many-to-many/48/1 "2018-09-03T13:55:23Z")

</div>

Hi!  
What is the best pattern to relate three tables (many-to-many relation) within Diesel?

For example let’s consider the following relation:  
users \<—\>\>users\_organizations\<\<—\>oranizations

Let’s say I want to create an organization. To support such relation I have to manually add ids of user and organization to **users\_organizations** table. Is there any better approach to implement such relation?  
let organization = insert\_into(organizations::table)  
.values(&new\_organization)  
.get\_result::(conn)  
.map\_err(|\_| error::ErrorInternalServerError(“Error creating organization”))?;

```
        let new_user_org = NewUserOrganizationIDs {
            user_id: msg.user_id,
            organization_id: organization.id,
        };

        insert_into(users_organizations::table)
            .values(&new_user_org)
            .get_result::<UserOrganization>(conn)
            .map_err(|_| error::ErrorInternalServerError("Error creating user-organization data"))

```

In case of selecting all organizations that relate to user (and vice verse) I came up with the following code:

```
let user = users::table.filter(users::id.eq(&msg.user_id))
            .get_result::<User>(conn)
            .map_err(|_| error::ErrorNotFound("User doesn't exist"))?;
        
        let user_organizations = UserOrganization::belonging_to(&user)
            .get_results::<UserOrganization>(conn)
            .map_err(|_| error::ErrorNotFound("User doesn't have any organization"))?;

        let mut organization_ids = vec![];
        for user_org in &user_organizations {
            organization_ids.push(user_org.organization_id);    
        }

        organizations::table.filter(organizations::id.eq_any(organization_ids))
            .get_results::<Organization>(conn)
            .map_err(|_| error::ErrorNotFound("Organizations don't exist"))
```
