Search code examples
graphqltypeorm

How to fix 'Cannot read property 'joinColumns' of undefined' error in EntitySchema and Graphql


I want to have a one-to-many relation in User to Keyword Table and in Keyword Table a many-to-one relation.

I don´t use TypeScript because that i have use the EntitySchema from Typeorm.

This was my entities:

import { EntitySchema } from 'typeorm';

export default new EntitySchema({
  name: 'User',
  columns: {
    id: {
      primary: true,
      type: Number,
      generated: true,
    },
    firstname: {
      type: 'varchar',
    },
    lastname: {
      type: 'varchar',
    },
    email: {
      type: 'varchar',
      default: null,
    },
    auth: {
      type: 'varchar',
      nullable: true,
    },
  },
  relations: {
    keywords: {
      target: 'Keyword',
      type: 'one-to-many',
    },
  },
});
import { EntitySchema } from 'typeorm';

export default new EntitySchema({
  name: 'Keyword',
  columns: {
    id: {
      primary: true,
      type: Number,
      generated: true,
    },
    name: {
      type: 'varchar',
    },
    created_at: {
      type: Date,
    },
  },
  relations: {
    user: {
      target: 'User',
      type: 'many-to-one',
    },
  },
});

The Error from GraphQL "Cannot read property 'joinColumns' of undefined"


Solution

  • There are two things missing in your EntitySchema: You need to specify the JoinColumn and the inverse side for the OneToMany relation. So this should work:

    export default new EntitySchema({
      name: 'User',
      ...
      relations: {
        keywords: {
          target: 'Keyword',
          type: 'one-to-many',
          inverseSide: 'user',
        },
      },
    });
    
    export default new EntitySchema({
      name: 'Keyword',
      ...
      relations: {
        user: {
          target: 'User',
          type: 'many-to-one',
          joinColumn: true,
        },
      },
    });