2015-11-04 17 views
0

控制器: 越來越帖子我如何獲取用戶名? (關係DB)

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原因$帖子是不是一個對象

and Post型號:

<?php 

命名空間應用程序\模型;

使用yii \ db \ ActiveRecord;

類柱延伸的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']); 
} 

}

+0

請張貼Post模型,並且給出了你想達到什麼樣的細節? –

+0

我想通過「user_id」屬性顯示用戶名。 –

+0

如果我錯了,請糾正我。我假設你想要做的是,如果user_id是2.那麼你想獲取對應於id 2的用戶記錄並顯示它的用戶名? –

回答

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