Tabular Input With Two Models, Second Table Needs Pk Of First

Hi All

I want to insert data into two tables from one form, a ‘student’ table that holds general info about students

and ‘classmember’ that is a junction table with ‘classroom’ table, because student can be in more than one classroom.

The ‘classmember’ table needs the the id from the student table which is not created until the student entry is created.

The ‘classmember’ table consists only of id, stu_id and class_id. The class_id will come from the form, id is auto incremented.

Here is the code so far that successfully inserts data into the student table:





    public function actionSignup() {


        if (isset($_POST['Student']) && isset($_POST['Classmember'])) {


            foreach ($_POST['Student'] as $i => $student_data) {

               

                $model = new Student;

                $model2 = new Classmember;

                $model->attributes = $_POST['Student'][$i];

                $valid = $model->validate();

                $model->save();

                $stu_id=Yii::app()->db->getLastInsertID();

                

            }

               

            if ($valid) {

                $this->redirect(array('index'));

            }

    }

    }



Just not sure how to combine the stu_id and the data from the form and get it into the classmember table.

Thanks

Hello. I’m just curious regarding the table structure, why would you use a blind integer key instead of using compound foreign key on an associative table (classmember) ? Since classmember does not have another meta information, I think it is best to use a compound foreign key :)

Anyway, regarding the signup action , you could do something like this :




public function actionSignup() {


        if (isset($_POST['Student']) && isset($_POST['Classmember'])) {


            foreach ($_POST['Student'] as $i => $student_data) {

               

                $model = new Student;

                $model->attributes = $_POST['Student'][$i];

                if($model->save()) {

                         $model2 = new Classmember;

                         $model2->attributes = $_POST['Classmember'];

                         $model2->stu_id = $model->stud_id; /* Now the stud_id of $model already containing the primary key generated by the database */

                         $model2->save();

                }

                ....

            }

         }

}



there is also a alternate way to save the values in the table.

setAttribute:

here is the link:

Thanks C.S.Putera, that works. Looking into compound foreign keys, have not used them before.

Thanks marjss will look into setAttribute as well.