这是我的代码:
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,
]);
如您所知,它在数据库中插入一个新行。现在我需要获得插入行的id
。我怎么能得到它?
注意到我知道,I can do the same if I use $obj->save()
, and the id will be $obj->id;
。但我想知道在使用create()
时我该怎么做。
答案 0 :(得分:2)
您可以使用代码
获取用户插入的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
}
create 方法返回已保存的模型实例
答案 1 :(得分:1)
答案 2 :(得分:1)
$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,
]);
在create
之后,$data->id
应该是最后插入的ID。
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
答案 3 :(得分:1)
此处create
和save
这两种方法都返回上次生成的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;
如果你想使用create方法,你必须在你的模型中将所有字段定义为可填写,并且在创建和编辑中都使用save()方法,所以习惯使用save方法是好的,
保存方法的例子
$user = User::first();
$user->email = 'updated@domain.com';
$user->save();
echo $user->id;
两个方法都返回最后插入的id。 我希望它有所帮助, 谢谢......