【问题标题】:How i can get username? (relation db)我怎样才能得到用户名? (关系数据库)
【发布时间】: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 的用户记录并显示其用户名?
  • 是的...但我已经回答了这个问题

标签: php mysql yii2


【解决方案1】:
<div class="col-lg-12">
    <? foreach($posts as $post){ ?>
        <h2><?= $post->user->username ?></h2>
        <p><?= $post->text ?></p>
    <? } ?>
</div>

【讨论】:

    猜你喜欢
    • 2014-08-25
    • 2023-03-22
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2018-03-16
    • 1970-01-01
    相关资源
    最近更新 更多