Save Data With Two Models

i have two tables category and category description and i want to save the data with one form…to save the details to two table…i’m generating models code for gii below is the code …

this is the category table model

<?php

/**

  • This is the model class for table "t_category".

  • The followings are the available columns in table ‘t_category’:

  • @property string $pk_i_id

  • @property string $fk_i_parent_id

  • @property string $i_expiration_days

  • @property string $i_position

  • @property integer $b_enabled

  • @property integer $b_price_enabled

  • @property string $s_icon

  • The followings are the available model relations:

  • @property TCategory $fkIParent

  • @property TCategory[] $tCategories

  • @property TLocale[] $tLocales

  • @property TCategoryStats $tCategoryStats

  • @property TItem[] $tItems

  • @property TKeywords[] $tKeywords

  • @property TMetaFields[] $tMetaFields

  • @property TPluginCategory[] $tPluginCategories

*/

class TCategory extends CActiveRecord

{

/**


 * @return string the associated database table name


 */


public &#036;s_name;


public &#036;s_description;


public &#036;i_expiration_days;





public function tableName()


{


	return 't_category';


}





/**


 * @return array validation rules for model attributes.


 */


public function rules()


{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


                    array('pk_i_id,i_expiration_days,b_enabled,b_price_enabled','required','on'=&gt;'Create'),


		array('b_enabled, b_price_enabled', 'numerical', 'integerOnly'=&gt;true),


		array('fk_i_parent_id', 'length', 'max'=&gt;10),


		array('i_expiration_days', 'length', 'max'=&gt;3),


		array('i_position', 'length', 'max'=&gt;2),


		array('s_icon', 'length', 'max'=&gt;250),


		// The following rule is used by search().


		// @todo Please remove those attributes that should not be searched.


		array('pk_i_id, fk_i_parent_id, i_expiration_days, i_position, b_enabled, b_price_enabled, s_icon', 'safe', 'on'=&gt;'search'),


	);


}





/**


 * @return array relational rules.


 */


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(


		'fkIParent' =&gt; array(self::BELONGS_TO, 'TCategory', 'fk_i_parent_id'),


		'tCategories' =&gt; array(self::HAS_MANY, 'TCategory', 'fk_i_parent_id'),


		'tLocales' =&gt; array(self::MANY_MANY, 'TLocale', 't_category_description(fk_i_category_id, fk_c_locale_code)'),


		'tCategoryStats' =&gt; array(self::HAS_ONE, 'TCategoryStats', 'fk_i_category_id'),


		'tItems' =&gt; array(self::HAS_MANY, 'TItem', 'fk_i_category_id'),


		'tKeywords' =&gt; array(self::HAS_MANY, 'TKeywords', 'fk_i_category_id'),


		'tMetaFields' =&gt; array(self::MANY_MANY, 'TMetaFields', 't_meta_categories(fk_i_category_id, fk_i_field_id)'),


		'tPluginCategories' =&gt; array(self::HAS_MANY, 'TPluginCategory', 'fk_i_category_id'),


	);


}





/**


 * @return array customized attribute labels (name=&gt;label)


 */


public function attributeLabels()


{


	return array(


		'pk_i_id' =&gt; 'Pk I',


		'fk_i_parent_id' =&gt; 'Fk I Parent',


		'i_expiration_days' =&gt; 'Expiration Days',


		'i_position' =&gt; 'I Position',


		'b_enabled' =&gt; 'B Enabled',


		'b_price_enabled' =&gt; 'B Price Enabled',


		's_icon' =&gt; 'S Icon',


	);


}





/**


 * Retrieves a list of models based on the current search/filter conditions.


 *


 * Typical usecase:


 * - Initialize the model fields with values from filter form.


 * - Execute this method to get CActiveDataProvider instance which will filter


 * models according to data in model fields.


 * - Pass data provider to CGridView, CListView or any similar widget.


 *


 * @return CActiveDataProvider the data provider that can return the models


 * based on the search/filter conditions.


 */


public function search()


{


	// @todo Please modify the following code to remove attributes that should not be searched.





	&#036;criteria=new CDbCriteria;





	&#036;criteria-&gt;compare('pk_i_id',&#036;this-&gt;pk_i_id,true);


	&#036;criteria-&gt;compare('fk_i_parent_id',&#036;this-&gt;fk_i_parent_id,true);


	&#036;criteria-&gt;compare('i_expiration_days',&#036;this-&gt;i_expiration_days,true);


	&#036;criteria-&gt;compare('i_position',&#036;this-&gt;i_position,true);


	&#036;criteria-&gt;compare('b_enabled',&#036;this-&gt;b_enabled);


	&#036;criteria-&gt;compare('b_price_enabled',&#036;this-&gt;b_price_enabled);


	&#036;criteria-&gt;compare('s_icon',&#036;this-&gt;s_icon,true);





	return new CActiveDataProvider(&#036;this, array(


		'criteria'=&gt;&#036;criteria,


	));


}





/**


 * Returns the static model of the specified AR class.


 * Please note that you should have this exact method in all your CActiveRecord descendants&#33;


 * @param string &#036;className active record class name.


 * @return TCategory the static model class


 */


public static function model(&#036;className=__CLASS__)


{


	return parent::model(&#036;className);


}

}

category description table model

<?php

/**

  • This is the model class for table "t_category_description".

  • The followings are the available columns in table ‘t_category_description’:

  • @property string $fk_i_category_id

  • @property string $fk_c_locale_code

  • @property string $s_name

  • @property string $s_description

  • @property string $s_slug

*/

class TCategoryDescription extends CActiveRecord

{

/**


 * @return string the associated database table name


 */


public function tableName()


{


	return 't_category_description';


}





/**


 * @return array validation rules for model attributes.


 */


public function rules()


{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


		array('fk_i_category_id, fk_c_locale_code, s_slug', 'required'),


		array('fk_i_category_id', 'length', 'max'=&gt;10),


		array('fk_c_locale_code', 'length', 'max'=&gt;5),


		array('s_name, s_slug', 'length', 'max'=&gt;100),


		array('s_description', 'safe'),


		// The following rule is used by search().


		// @todo Please remove those attributes that should not be searched.


		array('fk_i_category_id, fk_c_locale_code, s_name, s_description, s_slug', 'safe', 'on'=&gt;'search'),


	);


}





/**


 * @return array relational rules.


 */


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(


                


	);


}





/**


 * @return array customized attribute labels (name=&gt;label)


 */


public function attributeLabels()


{


	return array(


		'fk_i_category_id' =&gt; 'Fk I Category',


		'fk_c_locale_code' =&gt; 'Fk C Locale Code',


		's_name' =&gt; 'S Name',


		's_description' =&gt; 'S Description',


		's_slug' =&gt; 'S Slug',


	);


}





/**


 * Retrieves a list of models based on the current search/filter conditions.


 *


 * Typical usecase:


 * - Initialize the model fields with values from filter form.


 * - Execute this method to get CActiveDataProvider instance which will filter


 * models according to data in model fields.


 * - Pass data provider to CGridView, CListView or any similar widget.


 *


 * @return CActiveDataProvider the data provider that can return the models


 * based on the search/filter conditions.


 */


public function search()


{


	// @todo Please modify the following code to remove attributes that should not be searched.





	&#036;criteria=new CDbCriteria;





	&#036;criteria-&gt;compare('fk_i_category_id',&#036;this-&gt;fk_i_category_id,true);


	&#036;criteria-&gt;compare('fk_c_locale_code',&#036;this-&gt;fk_c_locale_code,true);


	&#036;criteria-&gt;compare('s_name',&#036;this-&gt;s_name,true);


	&#036;criteria-&gt;compare('s_description',&#036;this-&gt;s_description,true);


	&#036;criteria-&gt;compare('s_slug',&#036;this-&gt;s_slug,true);





	return new CActiveDataProvider(&#036;this, array(


		'criteria'=&gt;&#036;criteria,


	));


}





/**


 * Returns the static model of the specified AR class.


 * Please note that you should have this exact method in all your CActiveRecord descendants&#33;


 * @param string &#036;className active record class name.


 * @return TCategoryDescription the static model class


 */


public static function model(&#036;className=__CLASS__)


{


	return parent::model(&#036;className);


}

}

and my view having only two fields catname and category description

below is my view file…

<?php

/* @var $this TCategoryDescriptionController */

/* @var $model TCategoryDescription */

/* @var $form CActiveForm */

?>

<div class="form">

<?php $form=$this->beginWidget(‘CActiveForm’, array(

'id'=&gt;'tcategory-description-addcategory-form',


// Please note: When you enable ajax validation, make sure the corresponding


// controller action is handling ajax validation correctly.


// See class documentation of CActiveForm for details on this,


// you need to use the performAjaxValidation()-method described there.


'enableAjaxValidation'=&gt;true,

)); ?>

&lt;p class=&quot;note&quot;&gt;Fields with &lt;span class=&quot;required&quot;&gt;*&lt;/span&gt; are required.&lt;/p&gt;





&lt;?php echo &#036;form-&gt;errorSummary(&#036;model); ?&gt;


  

















&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'category Name'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'s_name'); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'s_name'); ?&gt;


&lt;/div&gt;


    


    &lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'category Description'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'s_description'); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'s_description'); ?&gt;


&lt;/div&gt;


    


    &lt;div class=&quot;row&quot;&gt;


        &lt;?php //echo &#036;form-&gt;labelEx(&#036;model,'Expiration Days');?&gt;


        &lt;?php //echo &#036;form-&gt;textField(&#036;model,'i_expiration_days');?&gt;


        &lt;?php //echo &#036;form-&gt;error(&#036;model,'i_expiration_days');?&gt;


    &lt;/div&gt;


    


&lt;div class=&quot;row buttons&quot;&gt;


	&lt;?php// echo CHtml::submitButton('Submit'); ?&gt;


           &lt;?php echo CHtml::submitButton(&#036;model-&gt;isNewRecord ? 'Create' : 'Save'); ?&gt;


&lt;/div&gt;

<?php $this->endWidget(); ?>

</div><!-- form -->

Hi

Just set in controller that save the models like that


if (isset($_POST['yourfirstmodel'])) {

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

$model->save();

}


if (isset($_POST['yoursecondmodel'])) {

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

$model2->save();

}

if the $model and $model2 has depedent attributes set those manually

PS: Please use code snipet in your code that you post :)

Thank u for ur reply…

i get the foreign key error how i get the primary key value from tcategory model and insert into tcategorydescription model …

i used this code in controller

$model2=fk_i_category_id=$model->pk_i_id;

$model2->save();

but it won’t works for me…

it’s right or any other way to get the primary key of one model and save the data to table how i do it…

and one more help i need json webservice restfull webservice if u have any example link plz send it to me…it save’s my life …

Hi, I am new to Yii Framework as well and I find this framework is very powerful and convenient.

Currently, I wish to insert data from an input form into two tables at a same time. I have generated the input form by Gii.

Here’s my database :

[color="#FF0000"]User[/color]

id | username | password | email

1 | admin | test1 | test@example.com

[color="#FF0000"]Lecturer[/color]

id | username | password | email | contact | profile

1 | aaa | test2 | test2@example.com | 11111 | aaa

Now, when i fill in the lecturer input form which is generated by Gii, I wish to insert the data of ‘username,password and email’ into user table at the same time too. However, it doesn’t works to me. I do not know what’s the error. Please help me~~

Here’s my code:

[color="#FF0000"]protected/controllers/LecturerController.php[/color]




....

public function actionCreate()

	{

		$model=new Lecturer;

                $model2=new User;


        if(isset($_POST['Lecturer'],$_POST['User']))

                {

                        // populate input data to $model and $model2

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

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

                        

                        // validate BOTH $model and $model2

                        $valid=$model->validate();

                        $valid=$model2->validate() && $valid;


		if($valid)

		{

			 $model->save(false);

                         $model2->save(false);

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

		}}


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

			'model'=>$model,

			'model2'=>$model2,

		));

	}



[color="#FF0000"]protected/views/lecturer/_form.php[/color]




<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'username'); ?>

		<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>128)); ?>

		<?php echo $form->error($model,'username'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'password'); ?>

		<?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>128)); ?>

		<?php echo $form->error($model,'password'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'email'); ?>

		<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>128)); ?>

		<?php echo $form->error($model,'email'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'contact'); ?>

		<?php echo $form->textField($model,'contact'); ?>

		<?php echo $form->error($model,'contact'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'profile'); ?>

		<?php echo $form->textarea($model,'profile',array('maxlength' => 300, 'rows' => 6, 'cols' => 50)); ?>

		<?php echo $form->error($model,'profile'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>



beginner123,

In your _form, you only have one model, how can you submit two _POSTs - $_POST[‘Lecturer’],$_POST[‘User’]).

Since you in Lecturer controller, so you can use below code to save User




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

                {

                        // populate input data to $model and $model2

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

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

                        

                        // validate BOTH $model and $model2

                        $valid=$model->validate();

                        $valid=$model2->validate() && $valid;

...



Thanks, Johnny Gan for correcting me! But, after I have changed into the code that you replied, it returns into another error which is ‘[color="#FF0000"]User has an invalid validation rule. The rule must specify attributes to be validated and the validator name.[/color]’ I could not understand the error.

I wish to insert the data of ‘username,password,email’ into User table as well after I have filled out the lecturer form and clicked submit. Please help me~~




...

public function actionCreate()

	{

		$model=new Lecturer;

        $model2=new User;

		// Uncomment the following line if AJAX validation is needed

		//$this->performAjaxValidation(array($model,$model2));

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

                {

                        // populate input data to $model and $model2

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

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

                        

                        // validate BOTH $model and $model2

                        $valid=$model->validate();

                        $valid=$model2->validate() && $valid;


                if($valid)

                {

                         $model->save(false);

                         $model2->save(false);

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

                }}


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

                        'model'=>$model,

                        'model2'=>$model2,

                ));


	}



Jii wat ur reply i did like that but i have some error …

public function actionCreate()

  {


     &#036;model=new TCategory;


     &#036;description =new TCategoryDescription;


     


     //perform ajx validation


     &#036;this-&gt;performAjaxValidation(&#036;model,&#036;description);


   


    if(isset(&#036;_POST['TCategory']))


     {


         &#036;model-&gt;attributes=&#036;_POST['TCategory'];


         &#036;model-&gt;save();


         


     }


     if(isset(&#036;_POST['TCategoryDescription']))


     {


          &#036;connection=yii::app()-&gt;db;


         &#036;sql=&quot;select * from t_category order by pk_i_id desc  limit 1&quot;;


        &#036;command=&#036;connection-&gt;createcommand(&#036;sql);


        &#036;row=&#036;command-&gt;queryRow();


        foreach(&#036;row as &#036;r)


        {


            &#036;fk_i_category_id=&#036;row[&quot;pk_i_id&quot;];


        }


         


         &#036;description-&gt;fk_i_category_id=&#036;fk_i_category_id;


         &#036;description-&gt;fk_c_locale_code='en_US';


         &#036;description-&gt;attributes=&#036;_POST['TCategoryDescription'];


        


         &#036;description-&gt;save();


     }


   


     


     &#036;this-&gt;render('create',array('model'=&gt;&#036;model,'description'=&gt;&#036;description));


  }

primary key constraints error …how i get the last inserted record id of t_cateogy table primary key value and at the same time i inserted the value in t_cetegory_description table…how i do that plz help me …

What is the message error ?

After save the first model, has its own id.

So if the model2 is depended by the first one then


if (isset($_POST['yourfirstmodel'])) {

   

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


  if ($model->save()) {

     if (isset($_POST['yoursecondmodel'])) {

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

       $model2->f_id = $model->id;

       $model2->save();

     }

  }

}

Hi all, I have a question here. How do I save part of the data into the second table?

For example,

Here’s my database :

[color="#FF0000"]User[/color]

id | username | password | email

1 | admin | test1 | test@example.com

[color="#FF0000"]Lecturer[/color]

id | username | password | email | contact | profile

1 | aaa | test2 | test2@example.com | 11111 | aaa

  1. I have a lecturer form to fill out and all the data will be saved into [color="#FF0000"]lecturer table[/color].

  2. I have another [color="#FF0000"]user table[/color] which has the same data as lecturer table of ‘username,password,email’.

  3. I wish to save the ‘username,password,email’ only into user table at the same time when save ‘username,password,email,contact,profile’ into lecturer table. How can I do that? Please help me~~

Here’s my code:




...

public function actionCreate()

	{

		$model=new Lecturer;

                $model2=new User;

		// Uncomment the following line if AJAX validation is needed

		//$this->performAjaxValidation(array($model,$model2));

         if(isset($_POST['Lecturer'],$_POST['User']))

          {

        // populate input data to $model and $model2

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

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

		 

		 if($model->save())	 

                         $model->username=$model2->username;

			 $model->password=$model2->password;

			 $model->email=$model2->email;

			 $model2->save();

                           

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

                }


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

                        'model'=>$model,

                        'model2'=>$model2,

                ));


	}






...

<?php echo $form->errorSummary(array($model,$model2)); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'username'); ?>

		<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>128)); ?>

		<?php echo $form->error($model,'username'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'password'); ?>

		<?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>128)); ?>

		<?php echo $form->error($model,'password'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'email'); ?>

		<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>128)); ?>

		<?php echo $form->error($model,'email'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'contact'); ?>

		<?php echo $form->textField($model,'contact'); ?>

		<?php echo $form->error($model,'contact'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'profile'); ?>

		<?php echo $form->textarea($model,'profile',array('maxlength' => 300, 'rows' => 6, 'cols' => 50)); ?>

		<?php echo $form->error($model,'profile'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


<?php $this->endWidget(); ?>



I couldn’t save any in my tables~ Please help me…thanks in advance!

thank u for ur reply…but now don’t get any error but the data also not saved in db…i used ur code …but i don’t get any error message and data not saved to database …

Trace your code like that


if (isset($_POST['yourfirstmodel'])) {

   

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


  if ($model->save()) {

     if (isset($_POST['yoursecondmodel'])) {

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

       $model2->f_id = $model->id;

       if ($model2->save()) {

       } else {

         echo CHtml::errorSummary($model2);

       }

     }

  } else {

    echo CHtml::errorSummary($model);

  }

}

i tried this code also but didn’t work at all… i don’t know how to do that …clearly say my problems …

first table having primary key second table having foreign key…

in my first table primary key category id …second table having category name and category description…

first table


|PK_id | Enabled |


| 1 | 1 |

| | |

|2 | 1 |

| | |

|

second table


categoryname | categorydescription | foriegnkey_id


          |                       |             


          |                       |


          |                       |

my problem is i have to insert the data in two table with same time …

i already show my model code and controller code and my view also …in that code if i insert the data getting error …or not displaying any error …

Please tell as what is the error message. If there is no error message then everything should be ok. Check also the data in your table database. Also f_id (second model) and id (first model) is corrected name ?

Post the models too

now i find my problems …i have two tables many-many relationship …one having composite primary key …

the composite primary key table i can’t able to create the CRUD using gii…

now i upload two models and controller file also …

i want the view only the second table field …if i give the value for categoryname,categorydescription it will affected the first table primary key also…