迭代CActiveDataProvider以从不同模型获取值

时间:2014-11-07 17:53:19

标签: php yii

我正在学习Yii。我正在尝试迭代CActiveDataProvider结果并从每个结果中获取一个索引的值,并使用它从另一个模型中提取数据。我不确定我是否正确处理它。

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,
    ));
}

当我使用dataProvider作为索引时,是什么导致我的结果为空?

1 个答案:

答案 0 :(得分:0)

对于这种情况,您应该使用Active Record关系。数据提供者可以自动考虑关系并加入数据。这是为了在Yii中有效使用Active Record而学习的重要概念,因此我建议阅读和练习示例。这是官方指南的链接:

http://www.yiiframework.com/doc/guide/1.1/en/database.arr

对于您的具体情况,关系看起来像这样:

专辑类关系功能:

class Album extends CActiveRecord{
    //beginning of model
    public function relations(){
        return array(
            'artist' => array(self::BELONGS_TO, 'Artist', 'artist_Id'),
        );
    }
    //rest of model
}

艺术家类关系功能:

class Artist extends CActiveRecord{
    //beginning of model
    public function relations(){
        return array(
            'albums' => array(self::HAS_MANY, 'Album', 'artist_Id'),
        );
    }
    //rest of model
}

控制器操作:

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,
    ));
}

通过将标准传递给相册数据提供者,告知其与艺术家“加”,所有艺术家和专辑将在1个SQL查询中获取。您可以从数据提供者访问Artist信息,例如,在视图文件的网格视图中访问:

$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',
        ),
    ),
));