Reputation: 902
I have two entities Projects & Orders. I want to have One-to-Many Orders in Projects and Many-to-One project in Orders.
Many-to-one side is working fine.
When I try to add One-to-Many in Project entity and try to fetch all, I get following error:
"Cannot read property 'joinColumns' of undefined"
Project Entity
const { EntitySchema } = require('typeorm');
const { BaseRelations, BaseColumns } = require('../BaseEntity');
module.exports = new EntitySchema({
name: 'Project',
columns: {
...BaseColumns,
name: {
type: 'varchar',
}
},
relations: {
...BaseRelations,
orders: {
type: 'one-to-many',
target: 'Order',
cascade: true,
},
},
});
Order Entity
const { EntitySchema } = require('typeorm');
module.exports = new EntitySchema({
name: 'Order',
columns: {
id: {
primary: true,
type: 'int',
generated: true,
},
name: {
type: 'varchar',
name: 'name',
},
},
relations: {
project: {
type: 'many-to-one',
target: 'Project',
joinColumn: {
name: 'project_id',
},
}
},
});
Upvotes: 4
Views: 4994
Reputation: 902
Figured it out. For anyone who is facing the similar issue. You will need to define inverseSide
in both entities schema. inverseSide
value should be the relation name defined in the entity on the other side of relation.
So for my entities above I will need to make the following changes:
Project Entity:
const { EntitySchema } = require('typeorm');
const { BaseRelations, BaseColumns } = require('../BaseEntity');
module.exports = new EntitySchema({
name: 'Project',
columns: {
...BaseColumns,
name: {
type: 'varchar',
}
},
relations: {
...BaseRelations,
orders: {
type: 'one-to-many',
target: 'Order',
cascade: true,
inverseSide: 'project' // Note that this is relation name, not the entity name
},
},
});
Order Entity:
const { EntitySchema } = require('typeorm');
module.exports = new EntitySchema({
name: 'Order',
columns: {
id: {
primary: true,
type: 'int',
generated: true,
},
name: {
type: 'varchar',
name: 'name',
},
},
relations: {
project: {
type: 'many-to-one',
target: 'Project',
joinColumn: {
name: 'project_id',
},
inverseSide: 'orders' // Note that this is the relation name in project entity, no the entity name Order
}
},
});
Upvotes: 10