yii2 mongodb - 向现有字段添加评论如何

yii2 mongodb - add comments to existing field how to

我有一个 collection 叫做 work-monitor where-in 我有两个字段 assignor_remarksassignee_remarks.

因此,当转让人或受让人提交评论时,我想将这些评论添加到相应的评论归档中。 我可以在 collection 中保存评论,但新评论会覆盖现有评论。

我的代码是这样的:

public function actionWorkUpdate($id)
      {
        \Yii::$app->request->enableCsrfValidation = false;
        $work = $this->modelClass::find()->where(['_id'=>$id])->one();

        $work->load(Yii::$app->getRequest()->getBodyParams(), '');

        $work->assignee_remarks = ["timestamp"=>date('d-m-Y h:i'),"comments"=>$work->assignee_remarks];
    $work->update();
    return "success";
  }

我怎样才能做到这一点。

像下面的例子一样更新:

"assignee_remarks":{"comment":"test comment","commentTime":2020-04-29 12.41},
{"comment":"test comment2","commentTime":2020-04-29 12.45},
{"comment":"test comment3","commentTime":2020-04-29 12.50}

如果我理解正确的话,试试类似的东西。

// In Work Model

public $assignee_remarks;

public function rules()
{
    return [
        //...
        ['assignee_remarks', 'safe'] // for free load
    ];
}

// In controller

/**
 * In bodyParams you have new comment like assignee_remarks: 'some text'
 * @param $id
 * @return mixed
 */
public function actionWorkUpdate($id)
{
    \Yii::$app->request->enableCsrfValidation = false;
    $work = $this->modelClass::find()->where(['_id' => $id])->one();

    $currentComments = $work->assignee_remarks ?? [];
    $work->load(Yii::$app->getRequest()->getBodyParams(), '');

    $currentComments[] = ["commentTime" => date('d-m-Y h:i'), "comment" => $work->assignee_remarks];
    $work->assignee_remarks = $currentComments;

    $result = $work->update();

    if ($result === false) {
        // validation error
    } else {
        return $result > 0 ? 'success' : 'fail';
    }
}