【发布时间】:2016-03-26 00:22:52
【问题描述】:
我已加入 2 个表,现在我想在字段 <th>Categories name</th> 中显示类别名称。我怎么能用 <?php foreach ($posts as $post){ ?> 做到这一点?我渲染像<?=$post->categories.name?> 吗?我被困在这里了。
谢谢。
我的控制器:
public function actionIndex()
{
$query = posts::find()->leftJoin('categories', 'posts.cate_id = categories.id');
$cates = Categories::find()->all();
$posts= $query->orderBy(['create_date' => SORT_DESC])->all();
$images = Images::find()->all();
$searchModel = new PostsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'posts' => $posts,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'cates' => $cates,
'images' => $images,
]);
}
我的看法:
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Create Date</th>
</thead>
<tbody>
<?php foreach ($posts as $post){ ?>
<tr>
<td><?= $post->id ?></td>
<th><?= Html::a($post->name, ['post/view', 'id'=>$post->id]) ?></th>
<td><?= $post->create_date ?></td>
</tr>
<?php } ?>
</tbody>
【问题讨论】:
标签: yii2 yii2-basic-app