我有这段代码在数据库中插入有关用户的信息:
DB::table('users')->insert(
array(
'first_name' => $first_name,
'last_name' => $last_name,
'birth_date' => $birthDate,
'email' => $email,
'password' => $password,
'profession' => $profession,
'gender' => $gender,
'age' => $age
)
);
它运行良好,然后我将用户重定向到信息中心页面。但是,我需要用户的 id 来获取有关他/她的信息。那么,如何在insert语句完成后返回id!
答案 0 :(得分:0)
使用insertGetId();
$id = DB::table('users')->insertGetId(
array(
'first_name' => $first_name,
'last_name' => $last_name,
'birth_date' => $birthDate,
'email' => $email,
'password' => $password,
'profession' => $profession,
'gender' => $gender,
'age' => $age
)
);
或只是laravel雄辩
$users = User::create([
'first_name' => $first_name,
'last_name' => $last_name,
'birth_date' => $birthDate,
'email' => $email,
'password' => $password,
'profession' => $profession,
'gender' => $gender,
'age' => $age
]);
dd($user->id); // If you modified Id add into model $primaryKey = "modified_id" $user->modified_id;