Yii2-高级:ArrayDataProvider

Yii2-advanced : ArrayDataProvider

我想将 ArrayDataProvider 与以下 siteController 代码一起使用。我写了下面的代码,但它不起作用。 这是我的 actionIndex :

public function actionIndex()
{
        $query = new \yii\db\Query;
        $query->select('*')->from('business_main_categories');
        $query->createCommand();

        $dataProviders = [];

        foreach ($query as $category) {
            $dataProviders[] = new ArrayDataProvider([
                'allModels' => $category,
                'sort' => false,
                'pagination' => false,
            ]);
        }

        return $this->render('index', [
            'dataProvider' => $dataProviders,
        ]);
}

并希望它在 gridView 中迭代。于是,我写了下面的代码(不知道对不对):

这是我的 index.php :

<?php
    $dataProviders[] = 'dataProvider';
    foreach ($dataProviders as $dataProvider) {
        echo GridView::widget([
            'dataProvider' => $dataProvider,
            'summary' => '',
            'columns' => [
                [
                        'attribute' => 'bmc_image',
                        'format' => 'html',
                        'label' => '',
                        'value' => function ($data) {
                            return Html::img($data['bmc_image'],
                                ['width' => '210px', 'height' => '190px']);
                        },
                    ],
                ]
       ]); 
    } 
?>

控制器

public function actionIndex()
{
    $query = new \yii\db\Query;
    $dataProvider = new ArrayDataProvider([
    'allModels' =>$query->from('business_main_categories')->all(),
    ]);

    return $this->render('index', [
        'dataProvider' => $dataProvider,
    ]);
}

索引

<?= GridView::widget([
        'dataProvider' => $dataProvider,
            'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
             [
              'attribute' => 'bmc_image',
              'format' => 'html',               
               'value' => function ($data) {
                    return Html::img($data['bmc_image'],['width' => '210px', 'height' => '190px']);
                   },
             ],
        ],
]); ?>

我没有使用 gridview 就解决了我的问题。如下-

我的站点控制器 -

public function actionIndex()
{
        $searchModel = new BusinessMainCategoriesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->pagination->pageSize = $dataProvider->getTotalCount();   //-1 : disable

        return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
        ]);
}

使用此代码,我从我的数据库中获取了 dataProvider 中的所有记录。 (请注意,我在 'BusinessMainCategoriesSearch' 模型中使用 ActiveDataProvider)

而且,我的 index.php 是 -

<?php
    $m = $dataProvider->getModels();
    foreach ($m as $dp) {
        echo "<img src = '".$dp['bmc_image']."' />";
        echo '<center><font color = "white">'.$dp['bmc_name'].'<font/></center>';
    } 
?>

这对我来说效果很好,而且这是最简单的方法。