如何修复TypeORM EntitySchema与GraphQL中的'Cannot read property 'joinColumns' of undefined'错误
Fix "Cannot read property 'joinColumns' of undefined" in TypeORM EntitySchema Relations
That error pops up because your TypeORM relationship definitions are incomplete—you're missing critical configuration for bidirectional association and explicit foreign key mapping. Let's fix this step by step.
Root Cause
TypeORM can't properly resolve the relationship mapping because:
- The one-to-many side (User) doesn't specify its inverse relation to the Keyword entity.
- The many-to-one side (Keyword) lacks an explicit foreign key column and join column configuration, which TypeORM needs to build the correct database relation.
Corrected Entity Schemas
User Entity Schema
Add the inverseSide property to the keywords relation to link it to the user field in the Keyword entity:
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', inverseSide: 'user' // Maps to the "user" relation in Keyword }, }, });
Keyword Entity Schema
- Add an explicit foreign key column (
userId) to the columns list. - Configure the
joinColumnproperty in theuserrelation to map to this new column, and optionally add theinverseSidefor clarity:
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 }, userId: { // Explicit foreign key column type: Number, nullable: true // Adjust based on your business logic (e.g., false if keywords must belong to a user) } }, relations: { user: { target: 'User', type: 'many-to-one', joinColumn: { name: 'userId' }, // Links to the "userId" column above inverseSide: 'keywords' // Optional but makes the bidirectional relation explicit }, }, });
Additional Steps
- Database Migration: If your database already exists, generate a migration to add the
userIdcolumn and foreign key constraint. Run this command (adjust based on your TypeORM config):
Then run the migration to apply changes:typeorm migration:generate -n AddUserIdToKeywordtypeorm migration:run - GraphQL Resolver Check: When querying related data in your GraphQL resolvers, make sure to use TypeORM's relation loading options (like
{ relations: ["keywords"] }for User queries, or{ relations: ["user"] }for Keyword queries) to ensure the associated entities are fetched correctly.
内容的提问来源于stack exchange,提问作者Julian-B90
相关产品推荐
相关产品推荐

