How to update data in the database without creating a new one?
async update ({ params, request, response }) {
const product = await Product.find(params.id)
product.name = request.input('name')
product.descr = request.input('descr')
product.qtd = request.input('qtd')
product.sub_descr = request.input('sub_descr')
product.price = request.input('price')
product.save()
return response.redirect('/')
}
This code is creating a new instance, the product.update()
method returns me an error
Adonisjs lucid supports automatic inserts & updates - meaning it intelligently updates or inserts a record based on the input.
According to the docs:
The save method persists the instance to the database, intelligently determining whether to create a new row or update the existing row.
However if you want to perform an update/bulk update you can always build a query as mentioned here .
But the problem you might face it
Bulk updates don't execute model hooks.
Example for Insert/Update:
const User = use('App/Models/User')
const user = new User()
user.username = 'virk'
user.email = 'foo@bar.com'
// Insert
await user.save()
user.age = 22
// Update
await user.save()
Example for Bulk Update:
const User = use('App/Models/User')
await User
.query()
.where('username', 'virk')
.update({ role: 'admin' })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.