V
V
Vladimir2022-04-21 21:31:29
PHP
Vladimir, 2022-04-21 21:31:29

Yii how are reviews (comments) implemented for a single post?

There is a page on it that displays the product, a form with fields Name Emel Text for sending feedback.
Well, below they are supposedly displayed.

6261a1cfd4496200769630.png
But if you go to another product, all these comments are also there.
I would like to have unique reviews on each page. What is needed for this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2022-04-22
@faradeifrontend

Solved by adding a new computer_id field to the reviews table.
And in the controller $review->computer_id = $id;

$comments = Review::find()->where(['computer_id' => $id]);

Full actionIndex
spoiler
public function actionIndex($id)
  {

    $model = new ReviewForm();

    if ($model->load(Yii::$app->request->post())) {
      if ($model->validate()) {
        $review = new Review();
        $review->setAttributes($model->getAttributes());
        $review->computer_id = $id;
        $review->save(false);

        Yii::$app->session->setFlash('success', 'Данные приняты');
        return $this->refresh();
      } else {
        Yii::$app->session->setFlash('error', 'Ошибка');
      }
    }

    $comments = Review::find()
      ->where(['computer_id' => $id]);

    $pagination = new Pagination([
      'defaultPageSize' => 5,
      'totalCount' => $comments->count(),
    ]);

    $comments = $comments->orderBy('id Desc')
      ->offset($pagination->offset)
      ->limit($pagination->limit)
      ->all();

    $computers = addComputer::findOne($id);

    return $this->render('index', compact('model', 'comments', 'pagination', 'computers'));
  }

V
vitaly_74, 2022-04-22
@vitaly_74

Based on your explanations, I can assume that you are getting $comments from somewhere,
this is probably some kind of request to the database.
and you need it like this:

$computer = addComputer::find()->where(['id'=>$idNumber])->one() //ужасно названный класс
$comments = $computer->comments;
//далее используйте тот код что вышe

and in the addComputer class itself, you need to add the following:
public function getComments(){
 return $this->hasMany(TableComments::class, ['computer_id'=>'id']);
}

documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question