how to use active record relations

Hey guys,

I have some questions to ask regarding active record relations. I have two tables; tbl_country(county_id(pk),country_name) and tbl_application(app_id(pk), nationality_id,…).

In my application view I want to replace the nationality_id and display the country_name base on the nationality_id.

How can I approach this using relations. I have tried different ways to fix this issue but I did not successes. One way that I have tried is as follow;

In my Application Model I have written this relation;

‘country’ =>array(self::HAS_ONE, ‘Country’, ‘nationality_id’)

In my Application Model I have written this relation;

‘country_all’ =>array(self:: BELONGS_TO, ‘Application’, ‘country_id’)

Can these relations be made? and how can I use the country_name as nationality in my application view? I have done the following but it did not work;

In my Application View

‘county.country_name’

Thanks in advance.

What’s the error message?

Why don’t you store the nationality in the country table?

Hi everyone,

I had same problem.

tbl_user(id, name…) tbl_post(id, userId…), by using auto generated view ‘index.php’ for model post. only show 2 fields(id, userId), how do I add user name field which from another table to here.

The relations has been writed inside both user and post model.

postControllor {








public function actionIndex()


{


        $dataProvider=new CActiveDataProvider('Post', array(


          'criteria'=>array(


            'with'=>array('user'),


          ),


        ));





        $this->render('index',array('dataProvider'=>$dataProvider));


}


}

inside index.php it is using CListView

<?php $this->widget('zii.widgets.CListView', array(


'dataProvider'=>$dataProvider,


'itemView'=>'_view',


)); ?>

And inside _view.php

 <?php  echo CHtml::encode($data->user->name); ?>





  **************** this give me a error, null object.

Thanks a lot.

never mind found solution.

Using Join instead with for criteria.

public function actionIndex()

{

$criteria = new CDbCriteria();

$criteria->join = "JOIN user ON user.id=userId";

$dataProvider=new CActiveDataProvider(‘Post’, array(

‘criteria’=>$criteria,

));

then inside the view file _view.php

access $data->user->name.

Hey Guys,

Finally,I succeed to fix the problem. I figured out the relations between the two table.The below scripts is the solution to my problem.

//Application Model

‘Country’ => array(self::BELONGS_TO,‘Country’,‘nationality_id’),

//Country Model

‘Country_All’ => array(self::HAS_MANY, ‘Application’, ‘nationality_id’),

//Application View

‘Country.country_name’

Peace…