In my database, I established a relationship between two tables: Users and Tasks. As per the Typeorm documentation.
Here are the Models:
@Entity('tasks')
class Tasks {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column({
type: 'varchar',
})
status: tasksStatus;
@ManyToOne(() => User, user => user.tasks)
user: User;
@Column()
description: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
@Entity('users')
class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@OneToMany(() => Tasks, task => task.user)
tasks: Tasks[];
@Column({
unique: true,
})
email: string;
@Column()
password: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
Next, let's look at the Repositories:
public async findAll(): Promise<Tasks[]> {
return this.ormRepository.find({ relations: ['user'] });
}
public async findByAll(): Promise<User[]> {
return this.ormRepository.find({
relations: ['tasks'],
});
}
However, when attempting to retrieve a user listing along with their associated tasks, the column value appears as null. Similarly, fetching tasks returns a null for the user attribute.
[
{
"id": "91d9c552-64e7-4f64-b6e8-b8cfc9c6323a",
"name": "Test of tests",
"status": "NEW",
"description": "test test test test test test test test test",
"created_at": "2021-04-16T11:23:01.144Z",
"updated_at": "2021-04-16T11:23:01.144Z",
"user": null
}
]
[ {
"id": "ba2673a6-1d76-4294-98d1-3dc4556733d7",
"name": "Wesley9",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88ffedfbe4edf1b9b1c8ede5e9e1e4a6ebe7e5">[email protected]</a>",
"password": "$2a$08$xTprPchGJj3vy3vRfa2P2OWHn5V.hqMh8gQn7323J1wi7WjeWXzbG",
"created_at": "2021-04-16T11:22:28.617Z",
"updated_at": "2021-04-16T11:22:28.617Z",
"tasks": []
}
]