【问题标题】:Iterating over CActiveDataProvider to get value from different model迭代 CActiveDataProvider 以从不同的模型中获取价值
【发布时间】:2014-11-07 17:53:18
【问题描述】:

我目前正在学习 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 作为索引时,是什么导致我的结果为空?

【问题讨论】:

  • 你能在调用渲染之前转储$this->name 的值并包含结果吗?另外,请附上您的看法index

标签: php yii


【解决方案1】:

您应该在这种情况下使用 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 查询中获取。您可以从数据提供者访问艺术家信息,例如,在视图文件的网格视图中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多