To add a column to the pivot table

In my project have a many-to-many relationship between a table Products and other Materials

In addition to the product id and the material id, I also need to save in the pivot table the amount of material of type float

ProductController:

  async store({ request }) {
    const { materials,...data } = request.only(['users_id', 'productName', 'productQuantity', 'productPrice', 'materials'])
    const product = await Product.create(data)
    if (materials && materials.length > 0) {
        await product.materials().attach(materials) 
        await product.load('materials')
      }
    return product
  }

Hi @gabrielgsv and welcome to the community! :slight_smile:

You can use second parameter of attach which is method for fiddleing with pivot table.
Second example in there:
https://adonisjs.com/docs/4.1/relationships#_attach

In your current case:

await product.materials().attach(materials, (row) => {
  row.amount = 12.34
})
1 Like

Thanks, I just needed help with this error that happens when I go to test the api

insert into "material_product" ("materialQuantity", "material_id", 
"product_id") values ($1, $2, $3) returning "id" - invalid input 
syntax for type real: "{"10","5"}"

Check over data that you are inserting. Most likely something is string that should be numberic.

Empty string throws error too, replace it with NULL