1=1 relation on table. creating partnered table entry using Active Record

Hello all,

I have read through this article several times and I guess I am missing something:

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

I have a table called ‘Persons’.

This has a column called ‘Type

I also have a table called ‘Student’ that has a 1=1 relationship with person.

When you enter a Person record, and the Person.Type is set to ‘Student’, I want a new record to get created in the Student table, with the same ID as the Person record, ready for use later.

This is what I tried in the Persons model, but it does not create the record:


    

public function afterSave($insert, $changedAttributes){

        if($insert && $this->type == 'Student'){

            $student_create = new Student();

            $student_create->id = $this->id;

            $student_create->save();

        }

        

    }

I can see in the article above how to retrieve relational data, but I could not see about creating it.

So I am hoping I am going down the right road here?

Do something like this…




	public function actionCreate()

	{

    	$model = new Persons;


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

       	// you saved the $model so now you have $model->IdPerson or whatever is your id key

      	if($model->Type=='Student') {

            	$student= new Students;

            	// here you set all students model value

            	$student->save();

      	}

.......



Thank you! Will try that. :)

It would appear that nothing is being created in the Student table still :(




use frontend\models\Student;


<.. more code ..>

//persons class controller code

<.. more code ..>




public function actionCreate()

    {

        $model = new Persons();


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

            if($model->type=='Student') {

                $student = new Student;

                $student->id = $model->id;

                $student->save();

        }

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }

Did you check if $model->type is exactly ‘Student’ and not ‘student’?

You can check your post value using yii2 debug.

if you enabled nice urls

http://mysite/debug

otherwise

http://mysite/?r=debug

Here you have the list of all the request made to your server, enter the detail of the request and check the post.

Nice! Will check that out when I get back home! Thank you.

For some reason the debug bar at the bottom of the screen is not showing and my debug data ends a few days ago.

This is despite the fact I have the folling in my index.php file:


defined('YII_DEBUG') or define('YII_DEBUG', true);

defined('YII_ENV') or define('YII_ENV', 'dev');

And in my modules I have added the following line:


'debug' => 'yii\debug\Module',

I am using an alias on my apache development server, so is it possble that somehow convinces the yii app that we are not running on localhost, and so hides the debug?

About the debug problem we will see but in the meantime you can do it in the old dirty way:




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

    echo "<pre>";

    print_r($app->request->post()); //this print the post content

    print_r($model); // this print the model just after you saved it

    echo "type: '".$model->type."'=='Student'\n";

    echo "</pre>";

    die(); // break execution before you enter the view,otherwise the buffer will be deleted and you don't get the output

    if($model->type=='Student') {

        $student = new Student;

        $student->id = $model->id;

        $student->save();

    }



Thanks! Will give that a go!

I have a DEV app on the same server that is using an Apache alias, and it’s got the debug bar fine.

Implying Apache alias has nothing to do with the debug bar disappearing, it’s probably a code corruption.

The code above is from a sandbox app (basically a copy of the DEV app), so I will refresh that with the code from the dev app and start over.

Then I will re-tackle the relation problem after the code refresh.

Right, finally had time to come back to this.

Just so you know, I had to start over, and now I have persons and students as my tables

here is what I am trying now when creating the Persons record, I’m just trying to create the students record for now regardless of what type is set to, just to see what happens:




 public function actionCreate()

    {

        $model = new Persons();

        $student = new Students();


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

            $student->personsPersonID = $model->personID;

            $student->setIsNewRecord(true);

            $student->save();

            return $this->redirect(['view', 'id' => $model->personID]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }




According to the debugger: "Model not inserted due to validation error"

Then AFTER that in the log it seems to do the insert into the Persons table.

So I think what’s happened is that the student record is trying to insert BEFORE the persons, and failing due to my foreign key constraints on the database.

Is there a way to perform the students insert AFTER the persons has completed?

You should check the rules in your student model. It give’s a validation error because you forget to insert data, or the given data is incorrect.

You can see what the problem is, getting the errors from the model. $student->validate(); $student->getErrors();

That is a very neat trick!


$student->validate(); 

print_r($student->getErrors());



So as it turned out the student record was failing validation on a required field.

As soon as I made the field a safe field, as it should have been, this is all working!

Thank you!