V
V
Viktor Yanyshev2018-02-08 10:38:19
Yii
Viktor Yanyshev, 2018-02-08 10:38:19

Sampling from a decompensated table?

There is a table with comments, has fields (output of comments in 2 levels):
ID | PARENT_ID (default NULL)| TOPIC_ID | .....
Topic model:

class Topic {
 ....
 public function getComments() {
   return $this->hasMany(Comments::className(), ['id' => 'topic_id']);
 }
}

Comment model:
class Comments {
....
public function getAnswer() {
return self::find()->where(['parent_id' => $this->id])->all();
}
}
In the view:
<? foreach($model->comments as $comment): ?>
 <div class="comment"><?= $comments->content  ?></div>

 <? if(!empty($comments->answer)): ?>

  <? foreach($comments->answer as $answer): ?>
    <div class="answer"><?= $answer->content ?></div>
  <? endforeach; ?>

 <? endif;?>

<? endforeach;>

With the current getAnswer() for some reason, it returns only 1 record of the answer to the comment, although in some cases there are more than 1, why is that? And is it possible to link the table? Type:
public function getAnswer() {
   return $this->hasMany(self::className(), ['id' => 'parent_id'])->where(['parent_id' => $this->id])->all();
 }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kim, 2018-02-08
@kimono

I think it's better to do this:

class Comments {
  /**
  * Ответы - это комментарии, у которых наш является родительским
  */
  public function getAnswers() {
    return $this->hasMany(self::className(), ['parent_id' => 'id']);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question