简体   繁体   English

在Laravel中获取插入行的ID

[英]Getting the id of inserted row in Laravel

Here is my code: 这是我的代码:

User::create([
    'name' => $request->name,
    'email' => $request->email,
    'cell_phone' => $request->cell_phone,
    'province_id' => $request->province,
    'city_id' => $request->city,
    'job' => $job,
    'company' => $company,
    'member_num' => $member_num,
]);

As you know, it inserts a new row in the database. 如您所知,它会在数据库中插入新行。 Now I need to get the id of inserted row. 现在,我需要获取插入行的id How can I get that? 我该怎么办?


Noted that I know, I can do the same if I use $obj->save() , and the id will be $obj->id; 注意,我知道, 如果我使用$obj->save() ,则可以执行相同的操作,并且ID为$obj->id; . But I want to know how can I do that when I'm using create() . 但是我想知道在使用create()时该怎么做。

You can get user inserted id using code 您可以使用代码获取用户插入的ID

$userDetials = User::create([
     'name' => $request->name,
     'email' => $request->email,
     'cell_phone' => $request->cell_phone,
     'province_id' => $request->province,
     'city_id' => $request->city,
     'job' => $job,
     'company' => $company,
     'member_num' => $member_num,
]);
if(isset($userDetials->id))    
{
    //if inserted 
    return $userDetials->id;
}
else
{
   //not inserted
}

The create method returns the saved model instance create方法返回保存的模型实例

As per the docs 根据文档

The create method returns the saved model instance: create方法返回保存的模型实例:

In your case it would be 在你的情况下

$user = User::create(...)
$data = User::create([
      'name' => $request->name,
      'email' => $request->email,
      'cell_phone' => $request->cell_phone,
      'province_id' => $request->province,
      'city_id' => $request->city,
      'job' => $job,
      'company' => $company,
      'member_num' => $member_num,
]);

After create , $data->id should be the last id inserted. create$data->id应该是最后插入的ID。

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);

Here create and save both method returns last generated id but make sure you are make the field auto increment. 在这里, createsave这两种方法都将返回上一次生成的ID,但请确保您使该字段自动递增。

$userobj = User::create([
'name' => $request->name,
'email' => $request->email,
'cell_phone' => $request->cell_phone,
'province_id' => $request->province,
'city_id' => $request->city,
'job' => $job,
'company' => $company,
'member_num' => $member_num,
]);
echo $userobj->id;

if you want to use create method you have to define all the fields as a fillable in you model, and save() method used in both for create and edit so habit of using save method is good, 如果您要使用create方法,则必须在模型中将所有字段定义为可填充字段,并且将save()方法用于创建和编辑,因此使用save方法的习惯很好,

example of save method 保存方法示例

 $user = User::first();
 $user->email = 'updated@domain.com';
 $user->save();
echo $user->id;

both method returns last inserted id. 两种方法都返回最后插入的ID。 i hope it helps, Thank you... 希望对您有所帮助,谢谢...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM