我正在尝试为我的注册用户创建一个配置文件页面。在这个页面上,Auth'用户数据将显示(姓名,电子邮件),但也有额外的个人资料信息(城市,国家,电话号码,…)。
我已经建立了一对一的关系,但我有一个问题。当创建一个用户时,我希望自动为该特定用户创建一个配置文件。
目前,我只是通过tinker添加了我的第一个用户的配置文件,但一旦我创建了第二个用户&转到配置文件页面,它给出了一个错误(看到配置文件尚未创建)。
在Profile.php中我有:
<?php namespace App;
use Illuminate'Database'Eloquent'Model;
class Profile extends Model {
protected $table = 'profiles';
protected $fillable = ['city', 'country', 'telephone'];
public function User()
{
return $this->belongsTo('App'User');
}
}
在User.php中我添加了:
<?php namespace App;
...
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
...
protected $table = 'users';
protected $fillable = ['name', 'lastname', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function Profile()
{
return $this->hasOne('App'Profile');
}
}
我像这样显示Profile数据(在我的Profile .blade.php页面上):
Full name: {{ Auth::user()->name }} {{ Auth::user()->lastname }}
E-Mail Address: {{ Auth::user()->email}}
City: {{ Auth::User()->profile->city}}
Country: {{ Auth::User()->profile->country}}
Phone number: {{ Auth::User()->profile->telephone}}
我猜我需要添加一些东西到'AuthenticatesAndRegistersUsers' trait和' registry .php'服务,但我不知道什么。
谢谢,
塞德里克
正如在你的问题的评论中所指出的,我认为最好的答案是将这两个模型合并为一个User模型。
但是,如果你想在用户创建时创建一个关系,你可以修改注册服务。
AuthenticatesAndRegistersUsers
trait将使用注册器(默认位于app/Services/Registrar.php
)来验证和注册用户。
你可以在这里修改create
方法,同时自动创建配置文件关系:
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user->profile()->save(new Profile);
return $user;
}
我想到了三个选择。
合并User和Profile表
为什么要将用户帐户从配置文件中分离出来?我想不出一个好的理由(不是说没有,我只是想不出一个)。合并这些表可以节省数据库查询,并完全解决这个问题。我认为这是最好的选择。
使用模型事件
创建User::created事件的监听器
User::created(function(User $user) {
$user->profile->save(Profile::create([... ]));
});
使用存储库
创建用户存储库来管理所有的数据库查询。然后在存储库创建方法中,您可以手动创建概要文件记录并将两者关联起来。然后使用注册器中的存储库,而不是直接使用模型