Example Not Working...

I did the example in the wiki

http://www.yiiframework.com/wiki/9/

The problem is i have two databases and when i call the model->save() function it is not saving to the correct database




<?php

class ActiveRecordLogableBehavior extends CActiveRecordBehavior

{

    private $_oldattributes = array();


    public function afterSave($event)

    {

        

        if (!$this->Owner->isNewRecord) {


            // new attributes

            $newattributes = $this->Owner->getAttributes();

            $oldattributes = $this->getOldAttributes();


            // compare old and new

            foreach ($newattributes as $name => $value) {

                if (!empty($oldattributes)) {

                    $old = $oldattributes[$name];

                } else {

                    $old = '';

                }


                if ($value != $old) {

                   

                    //$changes = $name . ' ('.$old.') => ('.$value.'), ';

                    //save the changes to the database

                    $log=new ActiveRecordLog;


                    $log->Create_DtTm = new CDbExpression('NOW()');

                    $log->UpdateType=       'CHANGE';

                    $log->AdminID=      Yii::app()->user->id;

                    $log->QtyAss=       $value;

                    $log->Was   =       $old;

                    $log->UserAffected = $this->Owner->getPrimaryKey();

                    $log->Game         = 'Clash';

                    $log->Description=  'User ' . Yii::app()->user->Name

                                            . ' changed ' . $name . ' for '

                                            . get_class($this->Owner)

                                            . '[' . $this->Owner->getPrimaryKey() .'].';

                    $log->save();

                }

                else

                {

                   //$changes = $name . ' ('.$old.') => ('.$value.'), ';

                    //save the changes to the database

                    $log=new ActiveRecordLog;


                    $log->Create_DtTm = new CDbExpression('NOW()');

                    $log->UpdateType=       'CHANGE';

                    $log->AdminID=      Yii::app()->user->id;

                    $log->QtyAss=       $value;

                    $log->Was   =       $old;

                    $log->UserAffected = $this->Owner->getPrimaryKey();

                    $log->Game         = 'Clash';

                    $log->Description=  'User ' . Yii::app()->user->Name

                                            . ' changed ' . $name . ' for '

                                            . get_class($this->Owner)

                                            . '[' . $this->Owner->getPrimaryKey() .'].';

                    $log->save();




                }

            }


        } 

    }


    public function afterFind($event)

    {

        // Save old values

        $this->setOldAttributes($this->Owner->getAttributes());

    }


    public function getOldAttributes()

    {

        return $this->_oldattributes;

    }


    public function setOldAttributes($value)

    {

        $this->_oldattributes=$value;

    }

}

?>



I am using this extension for the second database…




<?php


abstract class ToolActiveRecord extends CActiveRecord

{

    const BELONGS_TO='CBelongsToRelation';

    const HAS_ONE='CHasOneRelation';

    const HAS_MANY='CHasManyRelation';

    const MANY_MANY='CManyManyRelation';

    const STAT='CStatRelation';


    /**

     * @var CDbConnection the default database connection for all active record classes.

     * By default, this is the 'db' application component.

     * @see getDbConnection

     */

    public static $db;


    private static $_models=array();            // class name => model


    private $_md;                               // meta data

    private $_new=false;                        // whether this instance is new or not

    private $_attributes=array();               // attribute name => attribute value

    private $_related=array();                  // attribute name => related objects

    private $_c;                                // query criteria (used by finder only)

    private $_pk;                               // old primary key value


    /**

     * Returns the database connection used by active record.

     * By default, the "db" application component is used as the database connection.

     * You may override this method if you want to use a different database connection.

     * @return CDbConnection the database connection used by active record.

     */

    public function getDbConnection()

    {

        if(self::$db!==null)

            return self::$db;

        else

        {


            // Create CDbConnection and set properties

            self::$db = new CDbConnection();

            foreach(Yii::app()->db2 as $key => $value)

                self::$db->$key = $value;




        // Uncomment the following lines to prove that you have two database connections

        /*

            CVarDumper::dump(Yii::app()->db);

            echo '<br />';

            CVarDumper::dump(Yii::app()->db2);

            die;

        */

            if(self::$db instanceof CDbConnection)

            {

                self::$db->setActive(true);

                return self::$db;

            }

            else

                throw new CDbException(Yii::t('yii','Dawn Active Record requires a "db2" CDbConnection application component.'));

        }

    }

    

        protected function afterSave() {

             parent::afterSave();

        }


        

}


?>




Then my active record log class extends from the toolactiverecord because its in the other database…

I don’t get any errors and the regular update it works fine… maybe the aftersave is not being called?

I tried to ovverride after save and call parent::afterSave() in the ToolActiveRecord class but that doesnt work either.

Would appreciate any help!

Here is the class that extends the tool active record to log the info.




<?php

//user table stores sql logs

class ActiveRecordLog extends ToolActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @return Profile the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'adminlog';

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(


			'ID' => 'ID',

                        'Create_DtTm' => 'Create_DtTm',

			'AdminID' => 'AdminID',

			'UpdateType'    => 'UpdateType',

			'QtyAss' => 'QtyAss',

                        'Was'    =>   'Was',

                        'UserAffected'       =>   'UserAffected',

                        'Game' =>   'Game',

                        'Description' => 'Description'

		);

	}


	/**

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

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('ID',$this->ID);

                $criteria->compare('AdminID',$this->AdminID);


		return new CActiveDataProvider(get_class($this), array(

			'criteria'=>$criteria,

		));

	}

        





}




?>

I add the behavior to my model class like so…




        public function behaviors()

        {

             return array(

            // Classname => path to Class

            'ActiveRecordLogableBehavior'=>

                 'application.behaviors.ActiveRecordLogableBehavior',

        );

        }




Confused :(

I’m not sure about the big picture of what you are trying to accomplish, but you do not need an extension to access a second database in Yii. I have an app that talks to three databases without incident, and without extensions.

Your protected/config/main.php has a ‘db’ => array( … ) section, and you can add as many other ‘db1’ ‘db2’ ‘db3’ type sections as you like. They are all the same format as ‘db’ except the secondary ones have an additional ‘class’ => ‘CDbConnection’ in them.

This lets you define as many db connections as you like, for reference elsewhere. Let’s say you call yours ‘db2’ => array( … ).

Then, in the model that lives in the "other" db, you define:




   public function getDbConnection()

   {

      return Yii:app()->getDb2();

   }



Hi Thanks for the help,

it was actually not the code that was not working…

The sql guy gave me the wrong permissions so spent 3 hours on it for nothing lol everything works fine. :)