title: NestJs/TypeORM: How to save Many to Many
body: <p>I am trying to save a Many to Many relationship. Each entity by itself is working great.</p>
  <p>Here are the two entity files I am working with:</p>
  <pre><code>// location.entity
  
  @ManyToMany(type =&gt; User, user =&gt; user.locations, { eager: true, cascade: true })
  @JoinTable()
  users: User[];
  </code></pre>
  <pre><code>// user.entity
  @ManyToMany(type =&gt; Location, location =&gt; location.users, { eager: false })
  locations: Location[];
  </code></pre>
  <p>Here is the user repository:</p>
  <pre><code>// user.repository
  ...
  user.locations = locations;  // [1,2,3]
  user.uuid = uuidv4();
  
  try {
      await user.save();
        
      for (const location of user.locations) {
          locationsArray.push({ locationId: location, userId: user.id });
      }
  
      await user.locations.save(locationsArray);
  </code></pre>
  <p>Looking at <a href="https://orkhan.gitbook.io/typeorm/docs/many-to-many-relations" rel="nofollow noreferrer">this guide</a> makes it seem like I should be able to call <code>save()</code> on my relationship. In my case <code>user.locations.save(locations)</code>.</p>
  <p>However, that is returning an error:</p>
  <blockquote>
  <p>Property 'save' does not exist on type 'Location[]'.</p>
  </blockquote>
  <p>Using <a href="https://stackoverflow.com/questions/54885935/how-to-save-relation-in-manytomany-in-typeorm">this S.O thread</a> I know I need to loop through the array of location Id's and create the actual object I need to save:</p>
  <pre><code>[{ locationId: location, userId: user.id }]
  </code></pre>
  <p>I need to save the user <em>first</em> so I can get a userId.</p>
  <p>How can I save my relationship to my <code>location_users_user</code> table? Thank you for any suggestions!</p>
  <p><strong>EDIT</strong></p>
  <p>Thank you @Youba! See the solution below for more info.
  Hopefully this will help someone else...</p>
  <pre><code>// location.entity.ts
  
  ...
  
  @ManyToMany(type =&gt; User, user =&gt; user.locations, { eager: false })
  @JoinTable()
  users: User[];
  </code></pre>
  <pre><code>// user.entity.ts
  
  ...
  
  @ManyToMany(type =&gt; Location, location =&gt; location.users, { eager: false, cascade: true })
  locations: Location[];
  </code></pre>
  <p><code>cascade</code> is false by default. Enabling this will allow you to call the <code>save</code> method and the pivot table will update appropriately.</p>
  <p>You'll also need to pull in another module (user/locations etc). Thanks to Youba, you can <a href="https://stackoverflow.com/questions/65780539/nestjs-how-can-i-import-one-repository-into-another/65781724#65781724">see how to implement that here.</a></p>