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

The*_*d39 16 php mysql laravel laravel-5

我在Laravel中有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']),
        ]);
    }
Run Code Online (Sandbox Code Playgroud)

我想使用列id,current_food和current_level插入Users_Information

我有一个名为UserInformation的Users_Information控制器,我只是调用UserInformation :: create但是如何从User :: create获取id?

Ale*_*nin 38

尝试使用->id返回的对象,例如:

$id = $this->create($data)->id;
Run Code Online (Sandbox Code Playgroud)

  • @ TheGod39请将此答案设为已接受,以便用户快速查看正确的答案. (2认同)

Paw*_*zad 19

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,
]);
Run Code Online (Sandbox Code Playgroud)


小智 11

假设,我有一个模型名称Employee,我想在这个模型中插入一些数据,还想获取表 id。所以我可以通过下面的代码轻松实现这一点:

 $employee = new Employee();
 $employee->employeeName = 'Something';
 $employee->save();
 $employee->id;
Run Code Online (Sandbox Code Playgroud)


Fel*_*rte 6

另外,如果您不使用 Eloquent,您可以使用insertGetId

$id = DB::table('users')->insertGetId(
    [ 'name' => 'John Doe', 'email' => 'john@example.com']
);
Run Code Online (Sandbox Code Playgroud)


小智 6

使用 insertGetId(); 它为您提供插入行的 ID。

$userId = User::insertGetId([
    'name' => $request->input('name'),
     'email' => $request->input('email'),
     'password' => bcrypt($request->input('password')),
]);
Run Code Online (Sandbox Code Playgroud)

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


cam*_*ase 5

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
]);
Run Code Online (Sandbox Code Playgroud)

请注意,我们没有明确设置,user_id因为我们只是通过访问您定义的关系来创建信息; Laravel/Eloquent为您处理!