Yii2 列出类别中的项目

Yii2 list items inside a categories

我的控制器

public function actionIndex()
{
    $query = Documents::find();
    $docs = $query->orderBy('cate_id ASC')->all();
    return $this->render('index', [
        'docs' => $docs,
    ]);
}

我的观点

<?php foreach ($docs as $doc) {  
$cate = app\models\Categories::find()->where(['id'=>$doc->cate_id])->one();?>
    <h4><?=$cate->title?></h4>
    <p><?= Html::a($doc->title, ['documents/view', 'id'=>$doc->id]) ?></p>

<?php } ?>

有了这个我的观点看起来像

类别 1

类别 1

类别 2

我要显示

类别 1

类别 2

请帮我解决这个问题。

谢谢!

您的看法发生变化:

<?php 
foreach ($docs as $doc) {  
  $cate = app\models\Categories::find()->where(['id'=>$doc->cate_id])->all();?> // query for all records
  ?>
  <h4><?=$doc->title?></h4>
  <?php
  foreach ($cate as $cat {  
  ?>
  <p><?= Html::a($cat->title, ['documents/view', 'id'=>$cat->id]) ?></p>
  <?php
  }
}
?>

根据需要更改。

对于您的任务,使用 Yii ArrayHelper 可以很轻松地解决这个问题。

勾选这个linkhttp://www.yiiframework.com/doc-2.0/guide-helper-array.html

您可以使用 ArrayHelper::index 方法根据特定 key/column 对记录进行分组。

在您的情况下,您必须使用 'cate_id'(指的是您的类别 ID)对记录进行分组。

   //dont forget to import ArrayHelper before using it. 
   //use \yii\helpers\ArrayHelper.
   $catList = ArrayHelper::index($docs, null, 'cate_id');

以上代码将生成分组数组。例子....

   [
        1 =>[
              ['Menu Item Title 1','other column data','....'],
              ['Menu Item Title 2','other column data','....']
        ],
        2 =>[
              ['Menu Item Title 3','other column data','....'],
              ['Menu Item Title 4','other column data','....']
        ]

   ]

现在你遍历这个 array/array 对象。

     <?php
     foreach($catList as $cate_id => $catItems)
     {
        $cate = app\models\Categories::find()->where(['id'=>$cate_id])->one();
        echo '<h4>'.$cate->title.'</h4>';
        foreach($catItems as $catItem)
        {

           echo '<p>'.Html::a($catItem['title'], ['documents/view', 'id'=>$catItem['id']]).'</p>';
        }

     }
     ?>

在掌握了一些 Yii 代码之后,尝试用 Yii 方式编写代码。也就是说,在这种情况下,不要在View中写查询。

您可以使用模型 relation 来获取类别的名称。