'auto inserting a row to another table using TypeORM
I am using TypeORM in nestJS project which has users and each user has a cart. I have One-To-One relation between the users table and the carts table.
If I create a user I want the Cart to be automatically created and inserted into carts table and get its id and insert it into users table with the created user's info.
My question is, is there any way I can do that from the UserService
I have this User entity
import { Cart } from 'src/cart/cart.entity';
import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn('increment')
id: number;
@OneToOne(() => Cart, cart => cart.id)
cart_id: number;
@Column()
username: string;
@Column()
email: string;
@Column({ default: true })
password: string;
}
Also this Cart entity
import { CartItem } from 'src/cart_item/cart_item.entity';
import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
@Entity()
export class Cart {
@PrimaryGeneratedColumn('increment')
id: number;
@Column({ default: 0.00 })
total_price: number;
@OneToMany(
type => CartItem,
cartItem => cartItem.cart,
)
cartItem: CartItem[];
}
This is the user service:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
findAll(): Promise<User[]> {
return this.usersRepository.find();
}
findOne(id: number): Promise<User> {
return this.usersRepository.findOne(id);
}
async remove(id: number): Promise<void> {
await this.usersRepository.delete(id);
}
async add(user: User){
// write code here to create and insert a cart
// then get the cart id
// then add the id to "user" to be inserted
await this.usersRepository.insert(user);
}
}
this is the cart service:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cart } from './cart.entity'
@Injectable()
export class CartService {
constructor(
@InjectRepository(Cart)
private cartsRepository: Repository<Cart>
) { }
findOne(id: number): Promise<Cart> {
return this.cartsRepository.findOne(id)
}
findAll(): Promise<Cart[]> {
return this.cartsRepository.find()
}
async remove(id: number): Promise<void> {
await this.cartsRepository.delete(id);
}
public async create(cart: Cart) {// I want to call this function in UserService
await this.cartsRepository.insert(cart);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
