我正在尝试获取表的最后一个id,我想知道我的计数器的下一个数字是什么并将其显示给用户,我已经尝试了last()
方法,但我得到了这个:
>>> $trans = Transferencia::last()
BadMethodCallException with message 'Call to undefined method IlluminateDatabaseQueryBuilder::last()'
还有其他方法可以知道这一点吗?
在 Laravel 中获取最后插入 id 的 4 种方法:
使用insertGetId()
方法:
$id = DB::table('users')->insertGetId([
'name' => 'first'
]);
使用lastInsertId()
方法:
DB::table('users')->insert([
'name' => 'TestName'
]);
$id = DB::getPdo()->lastInsertId();
使用create()
方法:
$data = User::create(['name'=>'first']);
$data->id; // Get data id
使用save()
方法:
$data = new User;
$data->name = 'Test';
$data->save();
>>> $data = DB::select('SELECT id FROM transferencia ORDER BY id DESC LIMIT 1');
NVM
您可以使用 LAST_INSERT_ID(( 函数。试试这个:
SELECT LAST_INSERT_ID() INTO yourTableName;
保存后,$data->id 应该是最后插入的。
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
您可以使用以下代码:
$data['password']= md5($request->password);
$customer_id= DB::table('customer')
->insertGetId($data);
echo $customer_id;
正如我正确理解的那样,您想知道下一个插入中将出现哪个 id。如果表中有AUTO_INCREMENT主键,则可以使用查询获取该键的下一个值:
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = "TABLE_NAME"
但不建议在插入之前向用户显示其 ID,因为它可以从其他用户的会话中更改。
这可能是最好的答案:
$trans = Transferencia::orderBy('id', 'desc')->take(1)->first();
并使用$trans->id
.