automatically add user id to conjunction table

Hi all,

I have two tables:

  • tbl_user

  • table tbl_company

Because there is a many-to-many relationship, I also have a conjunction table tbl_company_has_tbl_user with the columns:

  • tbl_company_id

  • tbl_user_id

When the user is logged in, they can create a company. Whenever they do so, I would a record to be created in the conjunction table. I tried something in the controller but it didn’t work. I’m not sure how to access the fields of the conjunction table.

Any help would be much appreciated…

Model Company




	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

                        'tblUsers' => array(self::MANY_MANY, 'User', 'tbl_company_has_tbl_user(tbl_company_id, tbl_user_id)'),

		);



CompanyController




public function actionCreate()

	{

		$model=new Company;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Company']))

		{


                    //$tblUsers = new <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/huh.gif' class='bbc_emoticon' alt='???' />;

                    $tblUsers->tbl_company_id = $model->id;

                    $tblUsers->tbl_user_id = Yii::app()->user->id;


                    $model->attributes=$_POST['Company'];                        


                        if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}



You can use this http://www.yiiframework.com/extension/cadvancedarbehavior/ beahvior :)

Thanks for your reply. I’m too much of a beginner to figure out what code exactly I need to put where in the controller. Following the example in the link, I figured one line must be $model->tblUsers = Yii::app()->user->id;

Can you help me with the rest?

Thanks…

try this:





<?php 

public function actionCreate()

{

    $model=new Company;


    // Uncomment the following line if AJAX validation is needed

    // $this->performAjaxValidation($model);


    if(isset($_POST['Company']))

    {


        $tblUsers = new Company_has_tbl_user;

        //$tblUsers->tbl_company_id = $model->id;

        $model->user_id = Yii::app()->user->id;


        $model->attributes=$_POST['Company'];    


               

        $transaction = $model->dbConnection->beginTransaction();

        try{

            if($model->save())

            {

                $tblUsers->memberId =$model->user_id;

                $tblUsers->companyId =$model->companyId;

                $tblUsers->save();

            }

            $transaction->commit();						

            $this->redirect(array('view','id'=>$model->id));                     	

        }

        catch(CException $er)

        {

            $transaction->rollBack();

        }		

    }

    $this->render('create',array(

            'model'=>$model,

    ));

}






Thanks for your reply. Is this code using the cadvancedarbehavior?

it worked. However, in the conjunction table 2 records are created. If I remove $tblUsers->save(); it doesn’t save at all.

Thanks for your help.

It is because, we have used transaction during insertion. If insertion is failed in any one of table it automatically roll back its records, i.e. no records are inserted in the tables.

$tblUsers->save() is used to insert record for $tblUsers->save();.

Thanks. This is all a bit new to me, how can I avoid double insertion? And how would you use cadvancedarbehavior instead? It looks like it would require a bit less code?

Thanks…

If you want to use CAdvancedBehavior:

download

put the file in your /protected/extensions dir

in thr company Model add this funtion:


public function behaviors(){

          return array( 'CAdvancedArBehavior' => array(

            'class' => 'application.extensions.CAdvancedArBehavior'));

          }

Then you can do something like that:


public function actionCreate()

        {

                $model=new Company;


                // Uncomment the following line if AJAX validation is needed

                // $this->performAjaxValidation($model);


                if(isset($_POST['Company']))

                {


                    $model->tblUsers =  Yii::app()->user->id; //insert in the n:m table


                    $model->attributes=$_POST['Company'];                        


                        if($model->save())

                                $this->redirect(array('view','id'=>$model->id));

                }


                $this->render('create',array(

                        'model'=>$model,

                ));

        }

untested :)

if it doesnt work i have to look at my files at work ;)

Thanks for your help guys. Someone else suggested http://www.yiiframework.com/extension/save-relations-ar-behavior/ because apparently the other extension is a bit outdated. Here is the step by step instruction, which worked for me.

Scenario:

3 tables:

tbl_user (can have multiple companies)

tbl_company (can have multiple users)

=> tbl_company_has_tbl_user (joint table)

Steps:

  1. Extract the release file under protected/components

  2. Add the following code to the models you wish to add this behavior to:


public function behaviors(){

        return array('CSaveRelationsBehavior' => array('class' => 'application.components.CSaveRelationsBehavior'));

}



  1. Add the relation in the model Company, tbl_company_id has to come first as this id corresponds to the ID of the model



public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

                       'tblUsers' => array(self::MANY_MANY, 'User', 'tbl_company_has_tbl_user(tbl_company_id, tbl_user_id)'),

                );

	}



  1. Same as 3 but change to

'tblCompany' => array(self::MANY_MANY, 'Company', 'tbl_company_has_tbl_user(tbl_user_id, tbl_company_id)', 'index'=>'id'),




  1. For my particular case, I added this code to my controller CompanyController:



	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new Company;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Company']))

		{


                    //$model->companyHasTblUsers =  Yii::app()->user->id; //insert in the n:m table

                    $model->attributes=$_POST['Company'];

		    

                    

                    // for every new company, create a new record in the tbl_company_has_tbl_user

                    // with user id of logged in user and company id of newly created company

                    // depends on plugin CSaveRelationsBehavior.php in protected/components, which is loaded in

                    // protected/config/main.php and protected/models/user.php

                    // tblUsers is the name of the relation in this model

                    // tbl_user_id is the field that is not directly linked with this model (tbl_company_id is set automatically)

                    // Yii::app()->user->id is the id of the current user

                    $model->setRelationRecords('tblUsers', array('tbl_user_id'=>Yii::app()->user->id,));




                    if($model->save())





                                $this->redirect(array('view','id'=>$model->id));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}

Hope this will help someone in the future.