简体   繁体   中英

How to save two models in Yii2?

I have subscribe form where just 2 fields fio and email . I have default generated SubscribeForm model which return tableName = inf_users .

I get POST data, work with it and save to inf_users well. But now, i need to add the values to table act_courses after model->save previous table with structure:

  • id (PK)
  • ser_id (FK)
  • course_id (FK)
  • status (FK)
  • action_date (DATE)

What the table? I store all actions (orders) of users (online school). But now i have not working code without errors.

$model = new SubscribeForm();
$password = generateStrongPassword(12);
$model->password = md5($password);
$infUsersStatuses = $model->getStatuses('inf_users');
$model->status = $infUsersStatuses[0]->id;
$model->reg_date = date('Y-m-d');

if($model->load(Yii::$app->request->post())) {
    $actCoursesModel = new ActCourses();
    $infUser = $model->find()->where(['email' => Yii::$app->request->post('SubscribeForm')['email']])->one();
    $actCoursesModel->user_id = $infUser['id'];
    $actCoursesModel->course_id = $this->courseID;
    $actCoursesStatuses = $model->getStatuses('act_courses');
    $actCoursesModel->status = $actCoursesStatuses[0]->id;
    $actCoursesModel->action_date = date('Y-m-d');

    if ($model->save() && $actCoursesModel->save()) {
      ///someactions
    }

What am I doing wrong? I have data in inf_users , but no data in act_courses .

Thanks a lot!

PS getStatuses('act_courses') - return all available values which i can use for table

What am I doing wrong? I have data in inf_users, but no data in act_courses

Where are variable $act_courses definition, also $inf_users?

second:

$infUser = $model->find()->where(...);

Find before save?

third:

if($model->load(Yii::$app->request->post()))

load after assign some data?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM