我怎么能得到用户名? (关系数据库)

时间:2015-11-04 16:32:15

标签: php mysql yii2

控制器: 获得帖子

  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

命名空间app \ models;

使用yii \ db \ ActiveRecord;

类Post扩展了ActiveRecord {     / **      * @inheritdoc      * /     public static function tableName()     {         返回&#39;发布&#39 ;;     }

/**
 * @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']);
}

}

1 个答案:

答案 0 :(得分:1)

<div class="col-lg-12">
    <? foreach($posts as $post){ ?>
        <h2><?= $post->user->username ?></h2>
        <p><?= $post->text ?></p>
    <? } ?>
</div>