簡體   English   中英

Laravel:獲取 User::create 的 ID 並使用該 ID 插入新行

[英]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']),
        ]);
    }

我想用列idcurrent_foodcurrent_level插入到Users_Information

我有一個名為UserInformationUsers_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')),
]);

https://laravel.com/docs/5.7/queries#inserts

此外,如果您不使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM