How to get de pivot table data in model hook?

Hello!
I have the following tables in my system:
products; sales; sale_products.

When a sale is created I use attach method in the controller to make the relationship in the database:

async store ({ request, response, auth }) {
    try {
      const { products, ...data } = request.all()
      const trx = await Database.beginTransaction()

      data.user_id = auth.user.id

      const sale = await Sale.create(data, trx)

      await sale.products().attach(products.map(product => product.product_id), row => {
        row.price = products.find(product => product.product_id === row.product_id).price
      }, trx)

      await trx.commit()

      return response.status(201).json(sale)
    } catch (e) {
      await trx.rollback()

      return response.status(e.status).json({ error: e.message })
    }
  }

Now I have to subtract of the products table the quantity of each product that compose the sale. I have tried the something like the following code in the Sale model:

static boot () {
    super.boot()
    this.addHook('afterCreate', async sale => {
      sale.products().map(async product => {
        console.log(product)
      })
    })
  }

The problem is the pivot table data don’t appear in the console and the quantity that I have to subtract from products is in there.

Someone help please?

PS: Sorry my poor english.

Maybe you could run it like this

sale.products().withPivot(['quantity']).map(...)
1 Like