Home > database >  TypeOrm create OneToOne row
TypeOrm create OneToOne row

Time:10-16

Basic postgres typeorm nestjs question (that I somehow can´t find a solid answer to):
I have three example tables: customers, products, and orders. For this example orders only has two columns of product and column as oneToOne relations.

Now I want to do the basic step of creating an order. I have the customer id and the product id. Can`t I just put them in the corresponding columns? Do I really have to fetch the customer and product first?

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    @InjectRepository(Customer)
    private readonly customerRepository: Repository<Customer>,
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
  ) {}

  async newOrder(order: OrderDto) {
    const [customer, product] = await Promise.all([
      this.customerRepository.findOneBy({
        id: order.customer,
      }),
      this.productRepository.findOneBy({
        id: order.product,
      }),
    ]);

    const newOrder = this.orderRepository.create({
      customer,
      product,
    });
    return this.orderRepository.save(newOrder);
  }
}

CodePudding user response:

For this example orders only has two columns of product and column as oneToOne relations

I believe what you're trying to say is that each record in the orders has one linked record in customers and one linked record in products.

TLDR: You don't need to query either the customers or the products tables.


Make your Order entity class like the below and manually provide the foreign key columns. If you don't, TypeOrm will do this for you but the column names might be customer_id, and product_id.

@Entity('orders')
class Order {
  // Here provide the type based on `id` column in `Customer` entity.
  @Column({ type: 'varchar'})
  customerId: string;

  @ManyToOne(() => Customer)
  @JoinColumn({ name: 'customerId' })
  customer: Customer;

  // Here provide the type based on `id` column in `Product` entity.
  @Column({ type: 'varchar'})
  productId: string;

  @ManyToOne(() => Product)
  @JoinColumn({ name: 'productId' })
  product: Product;
}

Then in your service class, you can do this:

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
  ) {}

  async newOrder(order: OrderDto) {
    const newOrder = this.orderRepository.create({
      customerId: order.customer,
      productId: order.product,
    });
    return this.orderRepository.save(newOrder);
  }
}
  • Related