Yii 2.0 从没有小部件的模型中获取数据

Yii 2.0 Getting data from model without widget

谁能告诉我如何在不使用 Widget 的情况下从模型中检索数据的示例?因为需要获取每个 table 列的数据并将它们放在我自己的视图中(不使用小部件)

控制器:

public function actionIndex() {
        $searchModel = new B2CProductsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

查看:

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'id',
            'sku',
            'name',
            'short_description',
            'long_description',
            'thumb_img:ntext',
            'large_img:ntext',
            'url_content:ntext',
             'contact_info',
             'status',
            'currency',
             'price',
            'dimension',
            'weight',
            // 'created',
            // 'modified',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

上面的小部件遍历预定义网格视图中的元素, 但我想做的是:

foreach($data as $ab) {
   echo $ab->id;
}

你可以这样做:

/* assuming $data is an ActiveDataProvider object */
$models = $data->getModels(); 

foreach($models as $model) { ... }

see more here

如果您使用的是 ActiveDataProvider: 控制器:

public function actionMyAction()
{
    $dataProvider = new ActiveDataProvider([
        'query' => MyModel::find(),
    ]);

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

查看:

 <?php
  foreach ($dataProvider->models as $model){
            echo $model->myProperty;
        }  
 ?>

如果您使用的是 查询,例如:

    $query = (new \yii\db\Query())
        ->select('this, that')
        ->from('over_there');
    $command = $query->createCommand();
    $rows = $command->queryAll();

然后你可以像这样迭代结果(假设你将它传递给一个名为 $dataProvider 的视图):

  foreach($dataProvider as $data)
  {            
   $data['myProperty'];
  }