Drupal 7 DBTNG: How to retrieve the last INSERT id when using db_merge()
When using db_merge, it does not seem to be possible to retrieve the last insert ID if an INSERT was made.
MergeQuery::execute() returns MergeQuery::STATUS_INSERT if an insert was made, not the insert ID as InsertQuery::execute() does.
Is there an elegant way to retrieve the last insert ID when using db_merge?
Sources: 开发者_C百科http://api.drupal.org/api/drupal/includes--database--query.inc/function/MergeQuery%3A%3Aexecute/7 http://api.drupal.org/api/drupal/includes--database--query.inc/function/MergeQuery%3A%3Aexecute/7
Edit: Solved. modules/simpletest/tests/database_test.test contains a solution where we requery the database using known values to retrieve the record and fetch it's ID. Still seems odd there's no easier way to get the last insert ID, but this works for my purposes.
$result = db_merge('test_people')
->key(array('job' => 'Presenter'))
->fields(array(
'age' => 31,
'name' => 'Tiffany',
))
->execute();
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
$last_insert_id = $person->id; // Core test does not actually include an ID, but this is how it could work
精彩评论