mohit
mohit

Reputation: 1968

How to insert multi-level record in mongodb via yii2

For Example -
I have below record to be inserted in a collection

"panel_questions" : [
    {
        "question_id" : 1,
        "category_id" : 1
    },
    {
        "question_id" : 2,
        "category_id" : 1
    }
]

Through mongo I can achieve this by below query-

db.panel.update({"id":24},{$push:{panel_questions:{"question_id":2,"category_id":1}}});

But how we can make above mongo query in YII2

I have already tried below code but it didn't work

$this->update(
    [
             '$push'=>[
                         'panel_questions'=>[
                             'question_id'=>1,
                             'category_id'=>2
                         ]
                     ]
    ]
)

Upvotes: 1

Views: 805

Answers (1)

mohit
mohit

Reputation: 1968

After refreshing my mind with a beer :) I managed to append new array in mongodb
Here is what I did.

$question = [
                            'question_id'=>Yii::$app->request->post('question_id'),
                            'category_id'=>Yii::$app->request->post('category_id'),
                    ];

// From collection which is already saved.
$panel_questions = $panel->panel_questions;

// Pushing new question into already saved questions (merging)
array_push($panel_questions, $question);

// Assigning whole question array to data so we can load them in model.
$data['Panel'] =['panel_questions'=>$panel_questions];

if($panel->load($data) && $panel->validate()){
      if($panel = $panel->save()) {
              // do stuff
      }
}

Upvotes: 1

Related Questions