How i can get username? (relation db)

Wednesday, November 4, 2015

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











i can't use function getUser cause $post is not an object



and Post model:



<?php


namespace app\models;



use yii\db\ActiveRecord;



class Post extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function 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']);
}


}

0 comments:

Post a Comment