How do I insert a new entry into a table when another entry is created?

99 Views Asked by At

so I'm inserting req.body values into my Restaurant table with insertGraphAndFetch. On my Restaurant model I have a menu object with HasOneRelation. The menu table has a restaurantId, so what I'm trying to do is to create a menu entry with the restaurantId that was just created

export const createRestaurant: ExpressHandlerFn = async (req, res, next) => {
  try {
    const {
      name,
      description,
      address,
      cityId,
      priceTier,
      phoneNumber,
      schedule,
      tagIds,
    } = req.body;
    const { thumbnailImage, galleryImages } = req.files as MulterFields;
    const userId = req.session!.id;

    const createRestaurantTransaction = await Restaurant.transaction(async (trx) => {
      let newRestaurant = await Restaurant.query(trx).insertGraphAndFetch({
        name,
        description,
        priceTier,
        address,
        cityId,
        phoneNumber,
        schedule,
      });

this works fine and when I do the following, postman gets stuck on 'sending request':

newRestaurant.menu = await Menu.query().insert({
  restaurantId: newRestaurant.id,
});

Any help on this is much appreciated!

1

There are 1 best solutions below

0
On BEST ANSWER

You can use $relatedQuery method to insert a new menu entry for a just created restaurant instance:

await newRestaurant
  .$relatedQuery('menu')
  .insert({ food: 'someFood' });