例如 -
我有以下记录插入集合
"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}}});
但我们如何在YII2中进行上面的mongo查询
我已经尝试了以下代码,但它没有工作
$this->update(
[
'$push'=>[
'panel_questions'=>[
'question_id'=>1,
'category_id'=>2
]
]
]
)
答案 0 :(得分:1)
用啤酒刷新我的思绪:)我设法在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
}
}