Need Help Understanding Model Relations To Chtml::listdata Correlation

First off, I’m new to Yii and walking myself through Jeffrey’s book, Web Application Development with Yii and PHP.

I’m working to understand Models relations() and Drop box boxes. Questions are at the end.

Database structure:

  • User table with security_question_id (FK to SecurityQuestion id) and security_question_answer in it

  • SecurityQuestion with question column

User Model




class User extends TrackStarActiveRecord

{

...

    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(

                'issues' => array(self::HAS_MANY, 'Issue', 'requester_id'),

                'issues1' => array(self::HAS_MANY, 'Issue', 'owner_id'),

                'tblProjects' => array(self::MANY_MANY, 'Project', 'tbl_project_user_assignment(user_id, project_id)'),

                'securityQuestions' => array(self::BELONGS_TO, 'SecurityQuestion', 'security_question_id'),

            );

    }


    public function getSecurityQuestionOptions() {

        // WHY DO I NEED THIS? - This works.

        $questions = SecurityQuestion::model()->findAll();

        return is_null( $questions ) ? array() : CHtml::listData( $questions, 'id', 'question' );

        /**

         * Instead of this solution (which doesn't work)

         */

        // return CHtml::listData( $this->securityQuestions, 'id', 'question' );


    }

}



Here is the SecurityQuestion Model




class SecurityQuestion extends CActiveRecord

{

...

	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(

			'users' => array(self::HAS_MANY, 'User', 'security_question_id'),

		);

	}

}



Users Form _form.php:




...

<?php echo $form->dropDownList( $model,'security_question_id', $model->getSecurityQuestionOptions() ); ?>

...



Questions:

[list=1]

[*]Why can’t I access $this->securityQuestions to get the database rows vs. using model()->findAll()?




return CHtml::listData( $this->securityQuestions, 'id', 'question' );



[*]Doesn’t $this->securityQuestions reference to the SecurityQuestion model?

[/list]

Thanks for your help,

Whit

I get it now.




        $questions = SecurityQuestion::model()->findAll();

        return CHtml::listData( $questions, 'id', 'question' );



is the same as




        return CHtml::listData( $this->securityQuestions->findAll(), 'id', 'question' );



where SecurityQuestion::model() is the same as $this->securityQuestions. I just failed to put findAll() at the end of the second one. Ahha.