【问题标题】:Laravel User Authentication Scaffolding -> Saving data into two tablesLaravel 用户验证脚手架 -> 将数据保存到两个表中
【发布时间】:2018-01-09 00:07:15
【问题描述】:

我对 laravel 比较陌生,并且有一个需要一些手动配置的项目。

背景:

  • 使用身份验证脚手架(处理用户 注册和登录)
  • 我有两个表:Profile 和 Users。
  • 所有用户都有一个个人资料。
  • 但并非所有个人资料都有用户。

设置: 个人资料表 => id、姓名、头像等。 用户表 => profile_id、电子邮件、密码

由于 Laravel Auth (Scaffold) 处理注册和登录。我正在尝试在保存用户表之前将数据保存到配置文件表中。

protected function create(array $data)
{

    $profile = Profile::create
    ([
        'slug' => $data['name'],
        'name' => $data['name'],
    ]);

    $user = User::create
    ([
        'profile_id' => $profile->id,
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    return $user;
}

但这不起作用。并且错误消息告诉我查询中没有分配 profile_id。

我做错了什么?

【问题讨论】:

    标签: php laravel authentication laravel-5 laravel-5.4


    【解决方案1】:

    您的模型是如何设置的?如果 Eloquent 和您的数据库设置正确,您可以这样做:

    $profile = new Profile;
    $profile->slug = $data['name'];
    $profile->name = $data['name'];
    
    $profile->save();
    // At this point now you'll be able to get an ID of the profile
    
    $user = new User;
    $user->profile_id = $profile->id;
    $user->name = $data['name'];
    $user->email = $data['email'];
    $user->password = bcrypt($data['password']);
    
    $user->save();
    
    return $user;
    

    【讨论】:

    • 是的,这是我最初的想法,但我得到以下信息:SQLSTATE[HY000]:一般错误:1364 字段'profile_id'没有默认值(SQL:插入users( email,@,password,updated_at,created_at,created_at)值(John,John@gmail.com,$ 2y $ 10 $ nomolsl1sgek4enf2k2x7el2yo.to8o5uiricrzdzk9rlw4cvbk1u,2017-08:17,2017 -08-02 18:08:17))
    • 检查您的数据库迁移,您需要确保您的配置文件 id 列设置为 自动增量
    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2018-12-03
    相关资源
    最近更新 更多