Php yii2 mongodb-向现有字段添加注释如何
我有一个名为WorkMonitor的集合,其中我有两个字段:Php yii2 mongodb-向现有字段添加注释如何,php,mongodb,yii2,Php,Mongodb,Yii2,我有一个名为WorkMonitor的集合,其中我有两个字段: 转让人备注和受让人备注 因此,当转让人或受让人提交评论时,我想在各自的评论文件中添加这些评论。 我可以在集合中保存注释,但新注释将覆盖现有注释 我的代码如下: public function actionWorkUpdate($id) { \Yii::$app->request->enableCsrfValidation = false; $work = $this->mo
转让人备注
和受让人备注
因此,当转让人或受让人提交评论时,我想在各自的评论文件中添加这些评论。
我可以在集合中保存注释,但新注释将覆盖现有注释
我的代码如下:
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';
}
}
也许我理解你错了。您是否有多个字段注释?那么你的评论应该是一个数组?也许不是。当你们加载数据时,你们从bodyParams中设置了一个新的注释,然后把它写入数据库,只有新的数据,不是吗?在这种情况下,请在加载之前保存以前的数据,然后向其中添加新数据?否,备注是单个字段。请参阅我的相关更新。