例如-
我有以下记录要插入收藏
"panel_questions" : [
{
"question_id" : 1,
"category_id" : 1
},
{
"question_id" : 2,
"category_id" : 1
}
]
通过mongo,我可以通过下面的查询-来实现这一点
db.panel.update({"id":24},{$push:{panel_questions:{"question_id":2,"category_id":1}}});
但是我们如何在YI2中进行上述mongo查询
我已经尝试过下面的代码,但它不起作用
$this->update(
[
'$push'=>[
'panel_questions'=>[
'question_id'=>1,
'category_id'=>2
]
]
]
)
用啤酒提神后:)我设法在mongodb中添加了新数组
以下是我所做的。
$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
}
}