任何人都可以给我一些如何从模型中检索数据而不必使用Widget的示例吗?因为需要获取每个表列的数据并将它们放在我自己的视图中(不使用小部件)
控制器:
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'],
],
]); ?>
上面的小部件遍历预定义gridview中的元素, 但我想做的事情就是:
foreach($data as $ab) {
echo $ab->id;
}
答案 0 :(得分:3)
你可以这样做:
/* assuming $data is an ActiveDataProvider object */
$models = $data->getModels();
foreach($models as $model) { ... }
答案 1 :(得分:2)
如果您使用的是 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'];
}