3

Using Propel, I can save an object using

$user = new User;
$user->setName('Test');
$user->save();

$user->getId() will contain the ID of the inserted object. But this will only work if I use autoincremented ID values.

Is there any way I can get this to work when the IDs are generated by a function?

I can append RETURNING id to the end of the insert queries to return the ID, but I'm not sure whether I can get this data back into the Propel User object.

James
  • 565
  • 2
  • 7
  • 17
  • If it's generated by a function, can you get it before creating the object? and set it like `->setId($yourId)`? – Alex Tartan Nov 05 '15 at 16:38
  • It gets generated by a function in Postgres so doesn't exist until it has been inserted. – James Nov 05 '15 at 16:42
  • Noticed I can add `$this->id = $stmt->fetch()['id'];` into the `doInsert()` method in my Propel generated class which works but I'd love a nicer solution. – James Nov 05 '15 at 16:49

2 Answers2

2

You should be able to retrieve the missing (externally created) values by calling reload() on the object you wish to hydrate.

//hydrates fields by database values
$user->reload();
//should return the postgresql-generated-value
$user->getId();

edit: typos

Eelke van den Bos
  • 1,423
  • 1
  • 13
  • 18
  • 2
    Hi Eelke, I get an error saying `"Cannot find matching row in the database to reload object values."` when I try to do `reload()` after `save()`. Am I doing something wrong? – James Nov 11 '15 at 09:35
  • Hi James, sorry for the delay. Could you post your schema for this specific model? I once used a uuid_generate function to generate my primary keys and had no trouble retrieving the new value with the help of reload(). – Eelke van den Bos Dec 22 '15 at 10:52
0

If you're having a function or trigger in MySQL that creates for you a ID automatically on each insert then you need to save this generated value per session/connection. For example using last_insert_id(new_id), so you can fetch this value using SELECT last_insert_id(); through the current connection in PHP. There's no other logical way to fetch such generated IDs by functions/triggers.

Marc J. Schmidt
  • 8,302
  • 4
  • 34
  • 33