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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37075148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:02:58  来源:igfitidea点击:

Laravel: Get the ID of User::create and insert new row using that ID

phpmysqllaravellaravel-5

提问by TheGod39

I have AuthControllerin Laravel and I have 2 tables, one is Usersand one is Users_Informationand I want to insert into Users_Informationupon registration.

AuthController在 Laravel 有两张桌子,一张是Users,一张是Users_Information,我想Users_Information在注册时插入。

So I want to get the id from the following method and insert a new row and set the column ID of that row to the ID of the user I have just created.

所以我想通过以下方法获取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']),
        ]);
    }

I want to insert into Users_Informationwith a column id, current_foodand current_level

我想插入Users_Information一列idcurrent_food并且current_level

I have a controller for the Users_Informationcalled UserInformation, would I just call UserInformation::createbut how would I get the id from the User::create?

我有一个被Users_Information调用的控制器UserInformation,我会打电话UserInformation::create但我如何从 id 中获取 id User::create

回答by Alexey Mezenin

Try to use ->idof returned object, something like:

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

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

回答by Pawel Bieszczad

The create()method returns the model.

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,
]);

回答by camelCase

Eloquent has a nice way to handle saving relationships, which can be used in your case. It allows you to save a related model without accessing the model directly. Of course you must make sure your relationship is defined in the appropriate models first.

Eloquent 有一个很好的方法来处理保存关系,可以在你的情况下使用。它允许您在不直接访问模型的情况下保存相关模型。当然,您必须首先确保在适当的模型中定义了您的关系。

Below will create the user and their information. I assumed the method of your relationship was called informationbut you can adjust as needed.

下面将创建用户及其信息。我假设您的关系的方法被调用,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
]);

Notice that we did not explicitly set user_idbecause we simply created the information by accessing the relationship you have defined; Laravel/Eloquent handles that for you!

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

回答by Felippe Duarte

Also, if you are not using Eloquent, you can use insertGetId:

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

$id = DB::table('users')->insertGetId(
    [ 'name' => 'John Doe', 'email' => '[email protected]']
);

回答by Abid Shah

use insertGetId(); it gives you the id of an inserted row.

使用 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

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

回答by Md Shohag

Suppose, I have a model name Employeeand I want to insert some data in this model also want to get table id. So I can achieve this easily by below code:

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

 $employee = new Employee();
 $employee->employeeName = 'Something';
 $employee->save();
 $employee->id;