0

I'd like to get the ID of a project before saving in database... I know that the ID is generated during the saving but is there a solution?

var photo = dbContext.photo.build(photo);
console.log(photo.id); // doesn't work
photo.save().success(function(photo) {
    console.log(photo.id); // works
    callback(photo);
});
tonymx227
  • 5,293
  • 16
  • 48
  • 91
  • 1
    It's not really possible to get an ID before saving, unless you do a separate query for the highest ID and add 1. Why do you need the ID before saving? – Ben Fortune Apr 30 '14 at 10:07
  • I need the ID before saving to change the file name of the project... `projectID-DAY-MONTH-YEAR.png`, but I upload the file before saving and that's the problem... – tonymx227 Apr 30 '14 at 10:14

1 Answers1

1

Theoretically, you can query for the next id, generated by auto increment, see this How to get the next auto-increment id in mysql

However, remember that you have to do this within a transaction, where you lock the table before you query it, to prevent other processes from inserting and taking up the id that you just got. Have a look at https://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

However, this is going to get really, really complicated really, really quickly. Are you sure there is no other way to solve this problem? Can't you update the name after the record has been saved, that would be tremendously more easy?

Community
  • 1
  • 1
Jan Aagaard Meier
  • 28,078
  • 8
  • 95
  • 66
  • I found a best way, I save in my database, then I update the added data and then I upload my file and it works perfectly... – tonymx227 Apr 30 '14 at 15:01