CActiveDataProvider query with 'with', result not rendered

Hi guys,

I am trying to modify the actionindex to add a criteria like this:

$dataProvider=new CActiveDataProvider(‘Post’,

array(


	    'criteria'=>array(


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


	)


    )


);	

$this->render(‘index’,array(

'dataProvider'=>$dataProvider,

));

this works fine, but when I render the result, I don’t get any attribute of the author shown up.

so how can I show all the attributes from the join result query?

thanks in advance.

How do you try to access/render those attributes?

hi, thanks for your reply, I changed the index.php to cgridview. it is the as :


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

	'dataProvider'=>$dataProvider,

));

I tried adding something like


columns=>array('title','author_name')

,

an exception says authro_name is not defined. but the authro name is a column in my user’s table.

You’ll find the answer in the API reference.

/Tommy

Author is a ‘relation’ in your Post model. the post table itself does not have author_name.

Try something like this -


columns=>array(

'title',

array('name'=>'author', 'value'=>'@$data->author->author_name')

and as Tommy said, read the API documentation thoroughly

Hi, thanks for your pointer, I see it says:


'category.name',  // display the 'name' attribute of the 'category' relation

I tried to use author.name but this gives an empty string in the grid cell.

can you please help me again. thank u very much.

If you defined the relationship as post BELONGS_TO author and you have an attribute called name in author, it should work.

/Tommy

thanks, tommy, it works, I have one more question if you don’t mind, does this also apply to HAS_MANY relations? because you mentioned BELOGINS_TO relation.

Since you will get an array from the HAS_MANY relationship you can display one record (e.g the first one) by using the syntax $data->your_relation[0]->some_attribute.

For displaying all related records depends on what you want to do. E.g you could use a partial view for displaying them. One other solution may be to reverse the query to start from the HAS_MANY side (thus becoming a BELONGS_TO reference).

/Tommy

thank you very much, tommy, I tried and it works…