Displaying Data From Two Models

Hello everyone,

I have a User model with attributes id, first_name, last_name, sex, age. I also have a Message model with attributes sender_id, message_text.

In the message view i have a CGridView displaying all messages. In the ‘From’ column I currently have the sender_id from Message model.

Please will you show me how to display the sender’s first_name from the User model in the ‘From’ column. (please see images)

My code is as follows:-

Message model




public function relations()

	{

		return array(

		'sender' => array(self::BELONGS_TO, 'User', 'sender_id'),

		);

	}



Message view




$this->widget('zii.widgets.grid.CGridView', array(

	'dataProvider'=>$dataProvider,

	'columns'=>array(

		array (

			'name' => 'From',

			'type' => 'raw',

			'value' => 'CHtml::encode($data->sender_id)',

		),

		array(

			'name' => 'message_text',

			'type' => 'raw',

			'value' => 'CHtml::link(CHtml::encode($data->message_text), array("view", "id"=>$data->id))',

		

		),

	),

)); 



Message controller




public function actionIndex() {

  $model = new Message;


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

}






                array (

                        'name' => 'From',

                        'type' => 'raw',

                        'value' => 'CHtml::encode($data->sender->first_name)',

                ),



Dear shingionline

I hope the following is helpful.




$this->widget('zii.widgets.grid.CGridView', array(

	'dataProvider'=>$dataProvider,

	'columns'=>array(

		array (

			'name' => 'From',

			'type' => 'raw',

			'value' => '$data->sender->first_name',

		),

		array(

			'name' => 'message_text',

			'type' => 'raw',

			'value' => 'CHtml::link(CHtml::encode($data->message_text), array("view", "id"=>$data->id))',

		

		),

	),

)); 




edit:@keith .Sorry I was not aware of your reply.

Thank you very much Kieth, works perfectly :rolleyes:

Thank you very much for your response, it works perfectly

Good evening!

I have a question.

Is it possible show data in a view (detal when you click on id) of another table?

I explain better!

I have 2 tables

argomento (topic)


id_argomento

titolo_argomento

domande (question)


id

domanda

id_argomento

I my view I would like print the data connected with the id_argomento.

I took some code an the result is in the image I attached.

I would like see only the question with id 4.

Anyone have an idea?

Thanks for your help!

That should work!




$domandas=domandaModel::model()->findAll("id_argomento='$model->id'");


$dataProvider = new CArrayDataProvider($materiels);

$id_argomento='id_argomento';

$dataProvider->keyField=$id_argomento;


$this->widget('zii.widgets.grid.CGridView', array(

    'dataProvider'=>$dataProvider,

			

     'columns'=>array(


		 


  )  

));




Great it works ;)

Thank you very much ;D