I am hoping to streamline the process and avoid the need for a second database query when saving a row with a relationship. Users have the ability to create multiple events, and each user must go through authentication, allowing me access to their userID. I'm contemplating whether creating a relationship based on a specific User ID field would be more efficient than using the entire User object.
The structure of the Entity is as follows:
import {
Entity,
PrimaryGeneratedColumn,
Column,
JoinColumn,
ManyToOne,
} from 'typeorm';
import { User } from './User';
@Entity()
export class Event {
@PrimaryGeneratedColumn()
id: number;
@Column()
eventName: string;
@ManyToOne(() => User)
@JoinColumn()
createdBy: User;
}
export default Event;
Here is how it's handled in the Controller:
const userRepository = AppDB.getRepository(User);
const EventRepository = AppDB.getRepository(Event);
export async function addEvent(userID: number, eventObject: EventObject) {
const u = await userRepository.findOneByOrFail({ id: userID }); //Considering removing this line <---
const e = new Event();
Object.assign(e, eventObject);
e.eventStart = new Date(eventObject.eventStart);
e.eventEnd = new Date(eventObject.eventEnd);
e.createdBy = u; //Possibly simplifying to e.createBy = userID. <----
await EventRepository.save(e);
return e;
}