0
votes

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

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

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

}

1
please post the Post model and also give details on what you are trying to achieve? - Balaji Viswanath
I want to show username by "user_id" property. - Алексей Ягодаров
Please correct me if I'm wrong. I'm assuming that what you want to do is, if the user_id is 2. Then you want to fetch the user record that corresponds to id 2 and display its username? - Balaji Viswanath
yes... but I have already answered this question - Алексей Ягодаров

1 Answers

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