Drupal 7 DBTNG:如何在使用 db_merge() 时检索最后一个 INSERT id

发布于 2024-11-26 14:05:52 字数 539 浏览 2 评论 0原文

使用 db_merge 时,如果进行了 INSERT,似乎无法检索最后的插入 ID。

如果进行了插入,MergeQuery::execute() 返回 MergeQuery::STATUS_INSERT,而不是像 InsertQuery::execute() 那样返回插入 ID。

使用 db_merge 时是否有一种优雅的方法来检索最后一个插入 ID?

资料来源: 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

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:
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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陪你搞怪i 2024-12-03 14:05:52

编辑:已解决。modules/simpletest/tests/database_test.test 包含一个解决方案,我们使用已知值重新查询数据库以检索记录并获取其 ID。仍然看起来很奇怪,没有更简单的方法来获取最后一个插入 ID,但这对我的目的很有用。

$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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文