Hi,
I wanted to know if there was a better way of doing the following:
I have 2 tables, attribute and attribute_description.
-
attribute : contains an id
-
attribute_description : is linked to attribute by id_attribute and contains the name of the attribute and language_code (en, fr, etc…)
I want to generate dropdown lists in a loop for the attributes. But using Active Record i’m having problems because the name comes from another table.
Here is how I was able to make it work using Active Record and another using the normal method.
Active Record
I have to loop and generate an array before passing it to dropDownList function.
foreach (Tbl_Attribute::model()->findAllByAttributes(array('id_attribute_set'=>$value['id']),array(
'with' => array(
'tbl_attribute_description' => array(
'on' => 'tbl_attribute_description.language_code="'.Yii::app()->language.'"',
'together' => true,
),
),
)) as $row) {
$attributes[$row->id] = $row->tbl_attribute_description[0]->name;
}
echo $form->dropDownList($model,'product_attribute['.$index.'][id]', $attributes, array('class'=>'buttonsize'));
Normal method
$connection=Yii::app()->db; // assuming you have configured a "db" connection
$command=$connection->createCommand('SELECT
attribute.id,
attribute_description.name
FROM
attribute
LEFT JOIN
attribute_description
ON
(attribute.id = attribute_description.id_attribute AND attribute_description.language_code = "'.Yii::app()->language.'")
WHERE
attribute.id_attribute_set = "'.$value['id'.'"
ORDER BY attribute.sort_order ASC');
echo $form->dropDownList($model,'product_attribute['.$index.'][id]', CHtml::listData($command->queryAll(),'id','name'), array('class'=>'buttonsize'));
As you can see the normal method doesn’t have a loop to create the array it just generates the data directly using the listData function and the results returned from the query.
Both method work for me, the only thing is that the Active Record method requires an extra loop.
I am trying to get rid of that.
I tried telling listData to get the name from the other table by passing it’s alias but it doesn’t work.
Does anyone know how to achieve this?
Thanks!