php - 我如何获得用户名? (关系数据库)

标签 php mysql yii2

Controller : 获取帖子

  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 :显示帖子文本和用户 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 { /** * @继承文档 */ 公共(public)静态函数表名() { 返回“帖子”; }

/**
 * @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>

关于php - 我如何获得用户名? (关系数据库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33527102/

相关文章:

mysql - 尝试显示某个值在数据集中出现的实例总数

php - 菜单中的 Bad Nav::widget 编码,如何解决?

php - 我的 htaccess 文件不断出现 404 错误

php - 使用 Eloquent 将多个字段保存到数据库

php - 显示字段未完成的表单验证

MySQL SELECT COUNT > 0 作为 bool 值

activerecord - Yii2 从联结表中获取列并在 gridview 中使用

yii2 - 通过从 yii2 中的日期选择器输入来搜索数据

javascript - php - webscraping - 单击 ajax 调用然后抓取页面(可以在 python 中完成)

javascript - 如何将数据库查询打印到 javascript 数组?