[英]Laravel: Get the ID of User::create and insert new row using that ID
我在AuthController
中有 AuthController,我有 2 個表,一個是Users
,一個是Users_Information
,我想在注冊時插入Users_Information
。
所以我想通過以下方法獲取id並插入一個新行並將該行的列ID設置為我剛剛創建的用戶的ID。
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'username' => $data['username'] . ' ' . $data['username2'],
'mail' => $data['mail'],
'password' => bcrypt($data['password']),
]);
}
我想用列id
、 current_food
和current_level
插入到Users_Information
我有一個名為UserInformation
的Users_Information
控制器,我是否只調用UserInformation::create
但如何從User::create
獲取 id ?
嘗試使用->id
返回對象的->id
,例如:
$id = $this->create($data)->id;
create()
方法返回模型。
$user = User::create([
'username' => $data['username'] . ' ' . $data['username2'],
'mail' => $data['mail'],
'password' => bcrypt($data['password']),
]);
$userInfo = UserInformation::create([
'user_id' => $user->id,
'current_food' => $food,
'current_level' => $level,
]);
Eloquent 有一種很好的方法來處理保存關系,可以在您的情況下使用。 它允許您在不直接訪問模型的情況下保存相關模型。 當然,您必須首先確保在適當的模型中定義了您的關系。
下面將創建用戶及其信息。 我假設你們關系的方法叫做information
但你可以根據需要進行調整。
$user = User::create([
'username' => $data['username'] . ' ' . $data['username2'],
'mail' => $data['mail'],
'password' => bcrypt($data['password']),
])->information()->create([
'current_food' => $current_food,
'current_level' => $current_level
]);
請注意,我們沒有明確設置user_id
因為我們只是通過訪問您定義的關系來創建信息; Laravel/Eloquent 為您處理!
使用 insertGetId(); 它為您提供插入行的 ID。
$userId = User::insertGetId([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
此外,如果您不使用insertGetId
,您可以使用insertGetId
:
$id = DB::table('users')->insertGetId(
[ 'name' => 'John Doe', 'email' => 'john@example.com']
);
假設,我有一個模型名稱Employee並且我想在這個模型中插入一些數據也想獲取表 ID。 所以我可以通過以下代碼輕松實現這一點:
$employee = new Employee();
$employee->employeeName = 'Something';
$employee->save();
$employee->id;
請記住,如果您使用自定義 ID 設置表格,則必須在代碼中指明。 就我而言,我的表“Antecedentes”具有自定義 ID“ant_id”,因此“id”不起作用,不得不像這樣放置“ant_id”:
$success = Antecedentes::create($data)->ant_id;
我可以繼續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.