【问题标题】:How to get the row id after DB::insert in Lumen/Laravel with basic queries如何使用基本查询在 Lumen/Laravel 中的 DB::insert 之后获取行 ID
【发布时间】:2015-10-17 21:16:47
【问题描述】:

我正在使用 Lumen 5.1 并使用 DB 外观运行原始 SQL 查询。

执行insert 查询后如何获取行的ID?

例如:

$rowId = DB::insert("insert into `customers` (name) values ('Tom')");
echo $rowId; // 1

变量$rowId 应该包含数据库行的ID。

【问题讨论】:

  • 表中是否有一行设置为auto increment 列?
  • @RiggsFolly 是的,customers 表在id 列上设置为auto increment

标签: php laravel laravel-5 lumen


【解决方案1】:

我认为您可能需要获取底层 PDO 对象的句柄,然后我们才能像这样获取新的插入 ID

$pdo = DB::connection()->getPdo();

$result = DB::insert("insert into `customers` (name) values ('Tom')");

if ( $result )  {
    $rowId = $pdo->lastInsertId();
}

或者更简单

$result = DB::insert("insert into `customers` (name) values ('Tom')");
if ( $result )  {
    $rowId = DB::connection() -> getPdo() -> lastInsertId();
}

未经测试,只是根据手册推断

【讨论】:

  • 抱歉,我很忙。我试过了,它似乎工作。伟大的!非常感谢!
猜你喜欢
  • 2016-02-14
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2020-07-19
  • 2019-10-10
相关资源
最近更新 更多