Upsert embedded document in yiimongodbsuite

雨燕双飞 提交于 2019-12-04 10:23:12

You are inheriting from wrong class. To save document you must inherit from EMongoDocument not EMongoEmbeddedDocument. These classes are similar but have different purpose.

  • EMongoEmbeddedDocument Is for embedded documents only, it should be used only for embedded documents
  • EMongoDocument extends from EMongoEmbeddedDocument with methods to actually save data to db.

For array of comments, you have two options:

  1. Use plain php array - simple less maintanable, less power, erron prone..
  2. Use array of embedded documents - each comment is document, so can be validated, has rigid structure etc.

By default save/insert/update stores all attributes. For partial updates use combination of $attributes and set $modify to true. Warning: Passing array of attributes without $modify will store only passed attributes, discarding rest of document.

public function save($runValidation = true, $attributes = null)
...
public function insert(array $attributes = null)
...
public function update(array $attributes = null, $modify = false)
...

So in your case you can update like that:

$model->update(array('comments'), true);

Or if it's ok for you to ovverride whole document just save:

$model->save();

Note: for composite pk ovverride primaryKey():

public function primaryKey()
{
    return array('title', 'userid');
}

Uh, good that stackoverflow have drafts autosave feature:)

Finally I got solution in this way:

       $rec = $model->find($criteria)  ;
           if($rec){

       foreach($rec->edits as  $editarray){
            $var[]=$editarray;
       }
        $edits_new= new Medithtml();
        $edits_new['html']=$htm;
        $edits_new['ci']=$ci;
        $edits_new['path']=$path;  
        $var[]=$edits_new;
        $rec->edits=$var;

        $rec->userid=$userid;
        $rec->title=$title;
        $rec->update(array('edits'  ), true);
      }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!