glesage
glesage

Reputation: 975

Loopback before save update all instance

Hey all quick question about before save on UpdateAll

Hypothetically I have a customer model, that hasMany Orders. In an operation hook monitoring before save of the Customer I'm trying to create an order automatically. The trick is that I'm trying to do this when doing customers UpdateAll

Based on the docs I see there's no way to get the id of the current instance of the customer

But is there a way to do something like ctx.instance.orders.create(data); ?

Upvotes: 0

Views: 1455

Answers (2)

rc_dz
rc_dz

Reputation: 461

I believe in case like this, using persist hook will make more sense. You can access the id via ctx.currentInstance.id. This hook is triggered by operations that persist data to the datasource, including update.

MyModel.observe('persist', function(ctx, next) {
  if (ctx && ctx.currentInstance.id) {
    // create order here
  } 
  next();
});

Upvotes: 1

geek_guy
geek_guy

Reputation: 607

updateAll is an alias function of update.

You can try something like,

Customer.observe('before save', (ctx, next) => {
    if (ctx.instance && ctx.instance.id ) {
      // create order here
    }
    next();
  });

ctx.instance.id is avaialble only when you pass it.

i.e

Customer.update({id: 1}, {name: 'New Name'}) -in this case ctx.instance.id will be available.

Customer.update({name: 'New Name'}) - in this case ctx.instance.id won't be available. Also this will update name of all the customer.

Upvotes: 0

Related Questions