【问题标题】:Laravel - Create user profile with user idLaravel - 使用用户 ID 创建用户配置文件
【发布时间】:2014-09-09 16:48:15
【问题描述】:

在我的应用中,我有一个 users 表和一个 user_profiles 表。 创建新用户时,我需要在 user_profile 表中填写新用户 ID。

这是我的用户控制器中的存储功能

public function store()
{
    $userData = new User(Input::only('username'));
    $userProfileData = new UserProfile(Input::except('username'));


    $userData->save();
    $userProfileData->save();

    Flash::success('A new user has been created successfully.');
    return Redirect::route('users.index');
}

如何将新创建的用户 ID 传递给 users_profile 表中的 users_id 列?

【问题讨论】:

    标签: laravel-4


    【解决方案1】:

    获取和分配 ID 可能比您想象的要容易:

        public function store()
    {
        $userData = new User(Input::only('username'));
        $userProfileData = new UserProfile(Input::except('username'));
    
    
        $userData->save();
        $userProfileData->users_id = $userData->id;
        $userProfileData->save();
    
        Flash::success('A new user has been created successfully.');
        return Redirect::route('users.index');
    }
    

    id 将在 userData 对象上执行 save() 方法后在 $userData 对象中设置。然后,您可以将其分配给 user_profiles 对象中的外键。

    【讨论】:

    • 你是对的。我想多了。谢谢!
    猜你喜欢
    • 2015-06-24
    • 2012-07-14
    • 2020-12-12
    • 2013-07-04
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多