[英]How i can get username? (relation db)
Controller: getting posts 控制器:获取帖子
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
]
);
}
view: showing posts texts and user id's 视图:显示帖子文本和用户ID
<div class="col-lg-12">
<? foreach($posts as $post){ ?>
<h2><?=$post[user_id]?></h2>
<p><?=$post[text]?></p>
<? } ?>
</div>
i can't use function getUser cause $post is not an object 我不能使用功能getUser因为$ post不是对象
and Post model: 和后期模型:
<?php
namespace app\\models; 命名空间app \\ models;
use yii\\db\\ActiveRecord; 使用yii \\ db \\ ActiveRecord;
class Post extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'post'; 类Post扩展ActiveRecord {/ ** * @inheritdoc * /公共静态函数tableName(){return'post'; }
}
/**
* @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']);
}
} }
<div class="col-lg-12">
<? foreach($posts as $post){ ?>
<h2><?= $post->user->username ?></h2>
<p><?= $post->text ?></p>
<? } ?>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.