I'm currently learning Yii. I'm trying to iterate over CActiveDataProvider results and get the value of one index from every result and use that to pull data from another model. I'm not sure exactly if I'm going about it correctly.
public function actionIndex()
{
// This next line works and return data, but I want it to index with each record in $dataProvder
// $name = Artist::model()->findByPk(1);
$name = Artist::model();
$dataProvider=new CActiveDataProvider('Album');
foreach($dataProvider->getData() as $record){
$name->findByPk($record->artist_Id);
$this->name[] = $name->firstName . " " . $name->lastName;
}
$this->render('index',array(
'dataProvider'=>$dataProvider,
'name' =>$this->name,
));
}
What is causing my results to be blank when I use dataProvider for index?
You should be using Active Record relations for a situation like this. Data providers can take into account relations and join data automagically. This is a vital concept to learn in order to effectively use Active Record in Yii, so I suggest reading and practicing examples. Here's a link to the official guide:
http://www.yiiframework.com/doc/guide/1.1/en/database.arr
For your specific case, the relations would look something like this:
Album Class relations function:
class Album extends CActiveRecord{
//beginning of model
public function relations(){
return array(
'artist' => array(self::BELONGS_TO, 'Artist', 'artist_Id'),
);
}
//rest of model
}
Artist Class relations function:
class Artist extends CActiveRecord{
//beginning of model
public function relations(){
return array(
'albums' => array(self::HAS_MANY, 'Album', 'artist_Id'),
);
}
//rest of model
}
Controller Action:
public function actionIndex()
{
$names = array();
$dataProvider=new CActiveDataProvider('Album', array(
'criteria' => array(
'with' => 'artist',
)
));
foreach($dataProvider->getData() as $record){
$names[] = $record->artist->firstName . " " . $record->artist->lastName;
}
$this->render('index',array(
'dataProvider'=>$dataProvider,
'name' => $names,
));
}
By passing a criteria to the Albums data provider telling it to join "with" the artists, all artists and albums will be fetched in 1 SQL query. You can access the Artist information from the data provider, for example, in a Grid View in your view file:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
'name', // album name
'artist.firstName', // display the first name of the artist
array( // display the full name of the artist
'name'=>'fullName',
'value'=>'$data->artist->firstName." ".$data->artist->lastName',
),
),
));