如何在Lumen / Laravel中使用基本查询获取DB :: insert之后的行id

如何在Lumen / Laravel中使用基本查询获取DB :: insert之后的行id

问题描述:

I'm using Lumen 5.1 and running raw SQL queries, using the DB facade.

How can I get the row's id after performed an insert query?

For example:

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

The variable $rowId should then contains the db row's id.

我正在使用 Lumen 5.1 strong>并使用运行原始SQL查询 DB code>门面。 p>

如何在执行 insert code>查询后获取行的id? p>

例如: p> \ n

  $ rowId = DB :: insert(“insert into`custers`(name)values('Tom')”); 
echo $ rowId;  // 1 
  code>  pre> 
 
 

变量 $ rowId code>应该包含db行的id。 p> div>

I think you may have to get a handle to the underlying PDO object and then us that to get the new insert id like so

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

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

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

Or maybe even simplier

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

Not tested, just extrapolated from the manual