我在studentsController.php中有以下代码,可将数据从表单添加到2个表中,但出现错误。它是添加到学生表,然后也添加一些数据到用户表。我觉得我应该通过“ use”关键字在顶部添加一些内容,但我不知道。请帮助。
public function actionCreate() {
$model = new model();
$user = new Users();
if ($model->load(Yii::$app->request->post())) {
$model->id = Yii::$app->generateid->getGUID(); //this line caused the error
$model->save();
$studentId = $model->id;
if($user->load(Yii::$app->request->post()))
{
$user->id = $model->id;
$user->firstname = $model->firstname;
$user->lastname = $model->lastname;
$user->username = $model->phone;
$user->password = 'pass123'; //default password
$user->role = 'student';
$user->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
}
答案 0 :(得分:2)
您似乎在generateid
中想念web.php
应该是这样的
@ app / components文件夹中的GenerateIDs.php
<?php
namespace app\components;
class GenerateIDs extends \yii\base\Component
{
public function getGUID()
{
//do your stuff here
}
//....
}
然后在您的@app/config/web.php
中您有类似的东西
<?php
return [
'components' => [
'generateid' => [
'class'=>'app\components\GenerateIDs',
// other configurations for the component
],
],
];
然后您可以根据需要在应用中使用它
public function actionCreate() {
$model = new model();
$user = new Users();
if ($model->load(Yii::$app->request->post())) {
$model->id = Yii::$app->generateid->getGUID(); //this line caused the error
$model->save();
$studentId = $model->id;
if($user->load(Yii::$app->request->post()))
{
$user->id = $model->id;
$user->firstname = $model->firstname;
$user->lastname = $model->lastname;
$user->username = $model->phone;
$user->password = 'pass123'; //default password
$user->role = 'student';
$user->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}