接上一篇 基于yii2的blog系统开发2:

第七步 展示关联表字段

比如把post表里面的状态id换成状态名字显示,作者id换成作者名字显示
以文章详情页为例子:
修改backend/views/post/view.php

 <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'title',
            'content:ntext',
            'tags:ntext',
           // 'status',
            [
                'attribute'=>'status',
                'label'=>'状态',
                'value'=>$model->status0->name,
            ],
            'create_time:datetime',
            'update_time:datetime',
             //'author_id',
            [
                'attribute'=>'author_id',
                //'label'=>'作者',
                'value'=>$model->author->username,
            ],
        ],
     //自定义表格格式
      'template'=>'<tr><th style="width:80px">{label}</th><th>{value}</th></tr>',
        'options'=>['class'=>'table table-striped table-bordered detail-view'],
    ]) ?>

第八步 日期格式化显示

修改backend/views/post/view.php

[             'attribute'=>'create_time',
                'value'=>date('Y-m-d H:i:s',$model->create_time),
            ],

第九步 下拉菜单展示关联字段

以backend/views/post/update.php为例,这里面渲染了_form.php,修改这个_form.php文件:
<?= $form->field($model, 'status')->dropDownList([1=>'草稿',2=>'已发布'],['prompt'=>'请选择状态']) ?>
数据不能写死,要从数据库里面拿出来,所以应该这么写:

use common\models\Poststatus;
use yii\helpers\ArrayHelper;
......
<?php
        $data1 = Poststatus::find()->all();
        $data = ArrayHelper::map($data1,'id','name');
    ?>
    <?= $form->field($model, 'status')->dropDownList($data,['prompt'=>'请选择状态']) ?>

weixi老师另外介绍用QueryBuilder的方法

//$data = (new \yii\db\Query())->select(['name','id'])->from('poststatus')->indexBy('id')->column();
//推荐
$data = Poststatus::find()->select(['name','id'])->orderBy('position')->indexBy('id')->column();

关于Array Helper类

1.getValue

class User{public $name=’lq’;}
$array=[‘foo’=>[‘bar’=>new User()]];
php写法:
$value = isset($array['foo']['bar']->name)?$array['foo']['bar']->name:null;
ArrayHelper写法:
$value = ArrayHelper::getValue($array,'foo.bar.name');

2.getColumn

$data=[
['id'=>'123','data'=>'a'],
['id'=>'234','data'=>'b'],
];
$ids = ArrayHelper::getColumn($data,'id');
output:['123','234']

3.map

$result = ArrayHelper::map($data,'id','data');
output:['123'=>'a','234'=>'b']