分类表: category:[‘cid‘, ‘parent‘,‘category‘...]
新闻表:news: [‘id‘, ‘cid‘, ‘title‘...]
建立news与category的关系:使用gii的crud会自动生成如下代码:
Category:
public function getNews() { return $this->hasMany(News::className(), [‘cid‘ => ‘cid‘]); }
News:
public function getC() { return $this->hasOne(Category::className(), [‘cid‘ => ‘cid‘]); }
修改NewsController的index:
$dataProvider = new ActiveDataProvider([ ‘query‘ => News::find(), ]);
修改为:
$dataProvider = new ActiveDataProvider([ ‘query‘ => News::find()->with(‘c‘), //c即News: getC() ]);
然后再列表修改显示:
<?= GridView::widget([ ‘dataProvider‘ => $dataProvider, ‘columns‘ => [ [‘class‘ => ‘yii\grid\SerialColumn‘], ‘id‘, ‘c.category‘, //c.category就是分类名称 ‘title‘, ‘content:ntext‘, //‘image‘, // ‘keywords‘, // ‘description‘, [ ‘attribute‘ => ‘create_time‘, ‘format‘ => [‘date‘, ‘Y-m-d‘], ], // ‘update_time:datetime‘, ‘status‘, // ‘out_link‘, ‘sort‘, ‘click‘, // ‘lang‘, [‘class‘ => ‘yii\grid\ActionColumn‘], ], ]); ?>
原文地址:http://tang05709.blog.51cto.com/7146932/1946422