【发布时间】:2016-02-05 06:10:28
【问题描述】:
控制器: 获取帖子
public function actionIndex()
{
$posts = Post::find();
$pagination = new Pagination([
'defaultPageSize' => 2,
'totalCount' => $posts->count()
]);
$posts = $posts->offset($pagination->offset)->limit($pagination->limit)->all();
return $this->render(
'index',
[
'posts' => $posts,
'pagination' => $pagination
]
);
}
视图:显示帖子文本和用户 ID
<div class="col-lg-12">
<? foreach($posts as $post){ ?>
<h2><?=$post[user_id]?></h2>
<p><?=$post[text]?></p>
<? } ?>
</div>
我不能使用函数 getUser 因为 $post 不是一个对象
和帖子模型:
<?php
命名空间应用\模型;
使用 yii\db\ActiveRecord;
类 Post 扩展 ActiveRecord { /** * @inheritdoc */ 公共静态函数表名() { 返回“帖子”; }
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id', 'text'], 'required'],
[['user_id'], 'integer'],
[['text'], 'string']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'text' => 'Text',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
【问题讨论】:
-
请发布 Post 模型并详细说明您要达到的目标?
-
我想通过“user_id”属性显示用户名。
-
如果我错了,请纠正我。我假设您想要做的是,如果 user_id 为 2。那么您想获取对应于 id 2 的用户记录并显示其用户名?
-
是的...但我已经回答了这个问题