Laravel:获取 User::create 的 ID 并使用该 ID 插入新行

2022-08-30 12:45:39

我在Laravel有2张桌子,一张是,一张是,我想在注册时插入。AuthControllerUsersUsers_InformationUsers_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']),
        ]);
    }

我想插入到一列中,并且Users_Informationidcurrent_foodcurrent_level

我有一个被叫的控制器,我会直接调用,但我如何从中获取id?Users_InformationUserInformationUserInformation::createUser::create


答案 1

尝试使用返回的对象,如下所示:->id

$id = $this->create($data)->id;

答案 2

该方法返回模型。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,
]);

推荐