Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update all resulting models from a BookshelfJS collection?

Tags:

bookshelf.js

Given for example, a list of products with an attribute of sold_out, I would like to update a field of every item in that collection.

In this particular example, let's suppose I want to set the field sold_out = false to all items with that field set as true:

Product.where({sold_out: true})
.fetchAll()
.then(soldOutCollection => {
  return Promise.all(product => {
    return product.save({sold_out: false})
  })
})

This works, but it triggers one query per item in the collection.

Is there any way to update all items at once (triggering just one query)?

PS: I'm trying to avoid using knex.js directly

like image 832
Ramses Avatar asked Oct 15 '25 14:10

Ramses


1 Answers

I think if you want to update this way, you might want to try this:

Product
.where({sold_out: true})
.save(
    {sold_out: false}, 
    {method: 'update', patch: true}
 )
like image 118
websoftwares Avatar answered Oct 19 '25 12:10

websoftwares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!