Skip to content

Commit

Permalink
one to many added
Browse files Browse the repository at this point in the history
  • Loading branch information
batuhancetin1 committed Nov 11, 2023
1 parent e9b1476 commit a25ec42
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
7 changes: 5 additions & 2 deletions app/backend/src/poll/entities/poll.entity.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { User } from '../../user/entities/user.entity';
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';

// @Todo Some entities are not ready, therefore this is not the finalized version.
Expand All @@ -14,8 +17,8 @@ export class Poll {
@Column({ nullable: false })
question: string;

//@ManyToOne(() => User) // Establishing the many-to-one relationship
//@JoinColumn({ name: 'id' }) // Specifying the foreign key column
@ManyToOne(() => User, user => user.polls) // Establishing the many-to-one relationship
@JoinColumn({ name: 'creator_id' }) // Specifying the foreign key column
@Column({ nullable: false })
creator: string;

Expand Down
5 changes: 5 additions & 0 deletions app/backend/src/user/entities/user.entity.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import * as bcrypt from 'bcrypt';
import { Poll } from '../../poll/entities/poll.entity';
import {
Entity,
Column,
PrimaryGeneratedColumn,
BeforeInsert,
BeforeUpdate,
OneToMany,
} from 'typeorm';

const SALT_ROUNDS = 10;
Expand Down Expand Up @@ -32,6 +34,9 @@ export class User {
@Column({ nullable: true })
reset_password_token: number;

@OneToMany(() => Poll, poll => poll.creator)
polls: Poll[];

@BeforeInsert()
async hashPasswordBeforeInsert() {
if (this.password) {
Expand Down
9 changes: 7 additions & 2 deletions app/backend/src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ export class UserService {
}

public async findUserById(id: string): Promise<User> {
return await this.userRepository.findOneBy({ id });
return await this.userRepository.findOne({
where: {id: id},
relations: ['polls'],
});
}

public async createUser(user: CreateUserDto): Promise<User> {
Expand All @@ -37,7 +40,9 @@ export class UserService {
}

public async findAll(): Promise<User[]> {
return await this.userRepository.find();
return await this.userRepository.find({
relations: ['polls'],
});
}

public async verifyUser(email: string): Promise<void> {
Expand Down

0 comments on commit a25ec42

Please sign in to comment.