嵌套注释Yii2

时间:2018-06-30 19:08:21

标签: activerecord yii2

我有一个注释表,如下所示:

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| user_id   | int(11)      | NO   |     | NULL    |                |
| parent_id | int(11)      | NO   |     | 0       |                |
| post_id   | int(11)      | NO   |     | NULL    |                |
| body      | text         | NO   |     | NULL    |                |
| date      | datetime     | NO   |     | NULL    |                |
| status    | tinyint(1)   | NO   |     | 0       |                |
+-----------+--------------+------+-----+---------+----------------+

defautl的注释parent_id为0,如果回答了注释,则将parent id插入parent_id列中。

并使用以下代码与User Table建立关系:

public function getPosts()
{
    return $this->hasMany(Post::className(), ['category_id' => 'id']);
}

如何显示嵌套?

1 个答案:

答案 0 :(得分:1)

首先,您需要在 Comment 模型类中定义关系:

public function getChildComments()
{
    return $this->hasMany(self::className(), ['parent_id' => 'id']);
}

这定义了与其自身的实体关系。我认为将相关逻辑或处理程序也保存在同一类的帮助程序/可调用方法中总是很好的,而无需立即从数据库中全部加载它们。接下来会出现以下问题:

  

如何显示嵌套?


CASE01:在RESTFul应用程序内部

仅覆盖 Comment 类中的fields(),以始终输出子注释:

public function fields()
{
    $fields = parent::fields();
    $fields['childs'] = 'childComments';
    return $fields;
}

就是这样。 yii\rest\Serializer应该照顾到递归表示,在输出评论列表时,您会得到类似的东西:

enter image description here


案例02:在HTML Web视图中

可能有很多方法可以实现它。我能想到的最简单,最干净的方法是绑定Yii已经使用的模板引擎来以递归方式重新呈现包含子注释的视图。作为一个有效的示例,在您的 index.php 文件中添加如下内容:

<?php
use yii\helpers\Html;
use yii\widgets\ListView;
use yii\data\ActiveDataProvider;
use app\models\Comment;
?>

<?= ListView::widget([
    'dataProvider' => new ActiveDataProvider([
        'query' => Comment::find(),
    ]),
    'itemView' => '_comment',
    'itemOptions' => ['style' => 'padding: 10px 50px; border: 1px solid red'],
]); ?>

然后创建该 _comment.php 文件:

<?php
use yii\helpers\Html;
use yii\widgets\ListView;
use yii\data\ActiveDataProvider;
?>
    <div style="background-color: skyblue; padding: 5px 15px">
        <h4><?= Html::encode($model->id) ?></h4>
        <p><?= Html::encode($model->name) ?></p>
    </div>

    <?php
        if ($model->getChildComments()->count()) {
            echo ListView::widget([
                'dataProvider' => new ActiveDataProvider([
                    'query' => $model->getChildComments(),
                ]),
                'itemView' => '_comment',
                'itemOptions' => ['style' => 'padding: 10px 0 10px 50px; border: 1px dotted blue'],
            ]);
        }

    ?>

每当模板发现childComments链接到所代表的模板时,模板都会为其创建一个新实例。有了一点CSS填充来显示嵌套,该代码应输出以下内容:

enter image description here