-2

I have a table of products, and order_ID column that need to start from 5000

I have tried this:

if (record.Order_ID) {
  record.Order_ID = record.Order_ID + 1;
}
else {
  record.Order_ID = 5000;
}
galdin
  • 12,411
  • 7
  • 56
  • 71
liran
  • 3
  • 1
  • I believe we need to see more of the code, but would suggests you read the previous record's order ID and if there is no previous record set the ID to 5000. If there is a previous record with an ID, add one to that. Keep the previous and new records in different objects/variables. – Karl_S Aug 02 '17 at 12:16
  • that's what i've been trying to do... do you know how to get the previous record? and if there is no previous record wont it returns error? – liran Aug 02 '17 at 12:22
  • Take a look at the code in the [Simple Mail Merge tutorial](https://developers.google.com/apps-script/articles/mail_merge). Especially noting the `getRowsData()` function. This will read the data from a spreadsheet using a header row for the object keys. You could read all the data if needed or just a portion. – Karl_S Aug 02 '17 at 12:27
  • i dont understand how to get the previous record with this example can you please be more specific? – liran Aug 02 '17 at 16:47

1 Answers1

3

In case you need to implement it with Drive Tables:

// onCreate model's event handler 
// it receives about-to-create record as parameter
var ID_START_FROM = 5000;

var lock = LockService.getScriptLock();
// we need to lock our script, to prevent IDs inconsistency
// wait 3 seconds for script lock
lock.waitLock(3000);

// Run query to get latest ID
var query = app.models.Product.newQuery();
query.sorting.Id._descending();
query.limit = 1;

var records = query.run();
var next_id = records.length > 0 ? records[0].Id + 1 : ID_START_FROM;

record.Id = next_id;
// ...do other stuff

lock.releaseLock();

In case you are using Cloud SQL as data backend, you can easily alter your table:

ALTER TABLE Product AUTO_INCREMENT = 5000;
Pavel Shkleinik
  • 6,298
  • 2
  • 24
  • 36