How to access related attribute in listData?

I have 3 models: A, B, C

How can I access related attribute in listData from A Controller?


		

                $test=$_POST['A']['id_A'];

                $anAttribute=.......;

                $list=B::model()->findAll('anotherAttribute = :test', array(':test'=>$anAttribute));

                $list=CHtml::listData($list,'id_C','name');


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

			echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);

		}

Instead of name_B I want an attribute of C (B HAS_ONE C)

How can I do this? I tried:


$list=CHtml::listData($list,'id_C','B_to_C_relation.attribute');

and id_C is foreign key in B

But it shows the attribute as per id_B not id_C???

I tried anonymous function and same result…How can I solve it?

You could solve in this way:




$test=$_POST['A']['id_A'];

$anAttribute=.......;

$list=B::model()->findAll('anotherAttribute = :test', array(':test'=>$anAttribute));


foreach($list as $m)

{

      echo CHtml::tag('option',array('value'=>$m->id_<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='B)' />,CHtml::encode($m->B_to_C_relation->attribute),true);

}



Hi Fabrizio, same result…

The value is stored correctly but the names displayed in dropDown are not correct…

What is the content to be displayed?

Check content of $m->B_to_C_relation->attribute

I want to display an attribute (name) from C.

The relation is B HAS_ONE C.

B has:

-id_B

-…

-id_C

and C has:

-id_C

-name(this is the attribute I want to display)

-…

So what I want to do:




$list=B::model()->findAll('anotherAttribute = :test', array(':test'=>$anAttribute));

$list=CHtml::listData($list,'id_C','name');

Is it possible or I am mixing B and C?

In




$list=CHtml::listData($list,'id_C','name');



attribute ‘name’ doesn’t exist in B model.

Look carefully to this code:




$test=$_POST['A']['id_A'];

$anAttribute=.......;

$list=B::model()->findAll('anotherAttribute = :test', array(':test'=>$anAttribute));


foreach($list as $m)

{

      echo CHtml::tag('option',array('value'=>$m->id_<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='B)' />,CHtml::encode($m->B_to_C_relation->name),true);

}



if B_to_C_relation is a relation in B model.

Otherwise, post your B and C models.

It is like this:

  1. I findAll() in B and I want to take id_C from these records found.

  2. List all from C where id_C is equal to those found in step 1

  3. Access name in C

Sure, but you avoid to make an other for-cycle to have CHtml::listData.

How can I do it? please help

I have written.

If code works but content displayed is not correct, check attributes and relation’s attribute value.

Otherwise, post your B and C models.

The problem was the relation…It should be B belongs_to C not B has_one C

My stupid mistake!

Thank you for your help Fabrizio :)