Search code examples
typescriptpostgresqlnestjsbackendtypeorm

How create and add relation to two entities at same time


I am have two entites, Coupon and discount, each coupon can have many discounts,and each discount can have only one discount. I need two create new discount and coupon from one request,request body look like this

 "title": "someTitle",
  "description": "someDesc",
  "deadline": "someDeadline",
  "image": "someImg",
  "rules": "someRules",
  "company":"15",
  "category":"1",
  "discounts": [
    {
      "discount":"ad",
      "price":"awd"
    }
]

after this request, I need create new discount from provided array discounts,create new coupon ,and connect it coupon.entity.ts discount.entity.ts

coupon.service.ts

after this I am getting error error


Solution

  • You can do it by creating the discount first, and then adding it to the coupon entity. You can do this using an API route by first getting the discount data from the request, then making a new discount entity from it like so:

    createDiscount(req, res, { table: 'discount' }).then(async discountData => { const couponData = await createCoupon(req, res, { table: 'coupon', discountId: discountData.id }); return couponData; });```