所以我想尝试SignUp进入我的Yii应用程序。
但是,我却将用户表(用于登录)之间的关系转换为另一个表。这是关系:
表用户默认用于登录和注册。但是我想在user_profile表中插入另一个数据。我该怎么办?
编辑:
这些是我的代码:
SiteController.php
programming_classifier
SignupForm.php
public function actionSignup()
{
$model = new SignupForm();
$userProfileModel = new UserProfile();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
'userProfileModel' => $userProfileModel,
]);
}
signup.php
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
//$userProfileModel = new UserProfile();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
答案 0 :(得分:0)
一种实现目标的方法是:
-仅使用一种型号保持控制器清洁。
$model = new SignupForm();
-为用户个人资料添加其他字段作为SignupForm.php
的属性,并放置必要的规则以对其进行验证。
public $fullname;
public $dateOfBirth;
public $address;
...
public function rules()
{
...
[['fullname', 'dateOfBirth', 'address'], 'required'],
}
-将逻辑保存用户配置文件到signup()
函数中。
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$userProfile = new UserProfile();
$userProfile->fullname = $this->fullname;
$userProfile->dateOfBirth = $this->dateOfBirth;
$userProfile->address = $this->address;
return $user->save() && ($userProfile->userId = $user->id) !== null && $userProfile->save() ? $user : null;
}
-最后,在视图中添加用户个人资料字段。