How to iterate over Yii CActiveDataProvider object?

后端 未结 4 1080
礼貌的吻别
礼貌的吻别 2020-12-28 10:17

How to iterate over a dataprovider object? I want to access the \'name\' field of each row returned and build a list. Can you help?

Table structure for table

相关标签:
4条回答
  • 2020-12-28 10:38

    If you need itarate large data collection and you worry about memory usage do this:

    $dataProvider = new CActiveDataProvider('Categories');
    $iterator = new CDataProviderIterator($dataProvider);
    foreach($iterator as $category) {
       print_r($category);
    }
    

    CDataProviderIterator allows iteration over large data sets without holding the entire set in memory.

    some performance tests

    Test                        Time (seconds)          Memory (bytes)
    CDbDataReader               4.9158580303192         28339952
    CActiveRecord::findAll()    5.8891110420227         321388376
    CDataProviderIterator       6.101970911026          31170504
    
    0 讨论(0)
  • 2020-12-28 10:43

    Try this:

    public function returnCategoryNames()
    {
      $dataProvider= new CActiveDataProvider('Categories');
      $dataProvider->setPagination(false);
      //$count = $dataProvider->totalItemCount();
      $names = array();
      foreach($dataProvider->getData() as $record) {
        $names[] = $record->name;
      }
      return array_unique($names);
    }
    

    However you dont need to use a data provider, instead just use the model

    foreach(Categories::model()->findAll() as $record) {
    
    0 讨论(0)
  • 2020-12-28 10:43

    With the solution of @ben-rowe you are querying all the rows at once. You can have memory issues.

    With the following solution you will fetch the categories from ten by ten (the default CPagination.pageSize value):

            $dataProvider = new CActiveDataProvider('Categories', array(
                'pagination' => array(
                    'validateCurrentPage' => false
                ),
            ));
            $pagination = $dataProvider->pagination;
            while ($categories = $dataProvider->getData(true)){
                foreach ($categories as $category) {
                    //...
                }
                $pagination->currentPage++;
            }
    
    0 讨论(0)
  • 2020-12-28 11:01

    In Yii2 this has changed too:

        $searchModel = new ModelSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
        foreach($dataProvider->getModels() as $record) {
            echo $record->id . '<br>';
        }
    
        exit();
    

    Reference: getModels()

    0 讨论(0)
提交回复
热议问题