title: NestJS GraphQL: relational create mutation
body: <p>Using <code>@nestjs/graphql</code> I have introduced GraphQL to NestJS.<br />
  In one Mutation, I want to update the following two entities at the same time: &quot;User&quot; has many &quot;Car&quot;.<br />
  How should I write Service and Resolver?</p>
  <p>users/user.entity.ts</p>
  <pre class="lang-js prettyprint-override"><code>import { Column, PrimaryGeneratedColumn, Entity, OneToMany } from 'typeorm';
  import { Field, ObjectType } from '@nestjs/graphql';
  import { Car } from '../cars/car.entity';
  
  @Entity('users')
  @ObjectType()
  export class User {
    @PrimaryGeneratedColumn()
    @Field()
    id: number;
  
    @Column()
    @Field()
    name: string;
  
    @OneToMany(() =&gt; Car, (car) =&gt; car.owner)
    car?: Car;
  }
  </code></pre>
  <p>cars/car.entity.ts</p>
  <pre class="lang-js prettyprint-override"><code>import { Column, PrimaryGeneratedColumn, Entity, OneToMany } from 'typeorm';
  import { Field, ObjectType } from '@nestjs/graphql';
  import { User } from '../users/user.entity';
  
  @Entity('cars')
  @ObjectType()
  export class Car {
    @PrimaryGeneratedColumn()
    @Field()
    id: number;
  
    @Column()
    @Field()
    name: string;
  
    @ManyToOne(() =&gt; user, (user) =&gt; user.car)
    @JoinColumn({ name: 'user_id' })
    readonly owner?: User;
  }
  </code></pre>
  <p>users/dto/new-user.input.ts</p>
  <pre class="lang-js prettyprint-override"><code>import { Field, InputType } from '@nestjs/graphql';
  
  @InputType()
  export class NewUserInput {
    @Field()
    name: string;
  }
  </code></pre>
  <p>users/users.service.ts</p>
  <pre class="lang-js prettyprint-override"><code>import { Injectable } from '@nestjs/common';
  import { InjectRepository } from '@nestjs/typeorm';
  import { Repository } from 'typeorm';
  import { User } from './user.entity';
  import { NewUserInput } from './dto/new-user.input';
  
  @Injectable()
  export class UsersService {
    constructor(
      @InjectRepository(User)
      private usersRepository: Repository&lt;User&gt;,
    ) {}
  
    async add(newUserData: NewUserInput): Promise&lt;User&gt; {
      const newUser = this.usersRepository.create(newUserData);
      await this.usersRepository.save(newUser);
      return newUser;
    }
  </code></pre>
  <p>users/users.resolver.ts</p>
  <pre class="lang-js prettyprint-override"><code>import { Args, Mutation, Resolver } from '@nestjs/graphql';
  import { UsersService } from './users.service';
  import { User } from './user.entity';
  import { NewUserInput } from './dto/new-user.input';
  
  @Resolver()
  export class UsersResolver {
    constructor(private usersService: UsersService) {}
  
    @Mutation(() =&gt; User)
    public async addNewUser(
      @Args('newUserData') newUserData: NewUserInput,
    ): Promise&lt;User&gt; {
      return await this.usersService.add(newUserData);
    }
  }
  </code></pre>