title: setting up a one to many relationship for a self referencing table
body: <p>I have a <code>Project</code> entity with a non-autogenerated id field and a successor field. This successor is the project that follows next. But maybe there is no following project so this might be null.</p>
  
  <pre><code>@Entity()
  export class Project extends BaseEntity {
    @PrimaryColumn({ unique: true })
    public id: string;
  
    @OneToMany(() =&gt; Project, project =&gt; project.id, { nullable: true })
    public successorId?: string;
  }
  </code></pre>
  
  <p>When creating a new project via</p>
  
  <pre><code>public createProject(id: string, successorId?: string): Promise&lt;Project&gt; {
    const project: Project = new Project();
    project.id = id;
    project.successorId = successorId;
    return project.save();
  }
  </code></pre>
  
  <p>there are multiple cases I have to take care for.</p>
  
  <ul>
  <li><p>Passing in an id that already exists:</p>
  
  <p>This will not throw an error. It just overrides the existing entity.</p></li>
  <li><p>Passing in <code>undefined</code> for the <code>successorId</code>:</p>
  
  <p>The code works fine then but it does not create a <code>successorId</code> column with <code>null</code> then. The column simply does not exist in the database.</p></li>
  <li><p>Passing in the same id for <code>id</code> and <code>successorId</code> (this should be possible):</p>
  
  <p>TypeORM throws the error </p>
  
  <blockquote>
    <p>TypeError: Cannot read property 'joinColumns' of undefined</p>
  </blockquote></li>
  <li><p>Passing in a <code>successorId</code> of another existing project:</p>
  
  <p>I'm getting the same error as above</p></li>
  <li><p>Passing in a <code>successorId</code> of a project that doesn't exist:</p>
  
  <p>I'm getting the same error as above</p></li>
  </ul>
  
  <p>So how can I fix that? I think my entity design seems to be wrong. Basically it should be</p>
  
  <ul>
  <li>One project might have one successor</li>
  <li>A project can be the successor of many projects</li>
  </ul>
  
  <p>Would be awesome if someone could help!</p>
  
  <hr>
  
  <p><strong>Update</strong></p>
  
  <p>I also tried this</p>
  
  <pre><code>@OneToMany(() =&gt; Project, project =&gt; project.successorId, { nullable: true })
  @Column()
  public successorId?: string;
  </code></pre>
  
  <p>but whenever I want to call the <code>createProject</code> method I'm getting this error</p>
  
  <blockquote>
    <p>QueryFailedError: null value in column "successorId" violates not-null
    constraint</p>
  </blockquote>
  
  <p>and this</p>
  
  <pre><code>@OneToMany(() =&gt; Project, project =&gt; project.successorId, { nullable: true })
  public successorId?: string;
  </code></pre>
  
  <p>but then I'm getting this error</p>
  
  <blockquote>
    <p>TypeError: relatedEntities.forEach is not a function</p>
  </blockquote>