我想将一个数组插入到对象中,如下图所示,并嵌入到mongodb集合中:
[
[
"lat"=> 59.56555555455,
"lon"=> 35.54598994564,
"type"=> "manual"
],...
]
为实现这一点,我编写了以下代码。当我使用foreache
时确实有效,但是当我想在原始查询日志中使用InsertMany
时,它会向我显示插入的对象,但是当我检查数据库时,不会提交任何更改!我的错误在哪里?
日志 :
InsertManyResult {#302
-writeResult: WriteResult {#301}
-insertedIds: array:3 [
0 => ObjectId {#297
+"oid": "5bcd6d636925022398005981"
}
1 => ObjectId {#281
+"oid": "5bcd6d636925022398005982"
}
2 => ObjectId {#298
+"oid": "5bcd6d636925022398005983"
}
]
-isAcknowledged: true
}```
代码 :
$userTraffic = Auth::user()->userTraffic()->firstOrFail();
if ($userTraffic) {
$userTraffic->traffics()->raw( function ( $collection ) use ($traffic) {
$data= $collection->insertMany($traffic);
dd($data);
return $data;
});
/* foreach ($traffic as $field) {
$userTraffic->traffics()->create($field);
}*/
return response(['status'=>true,'UserID:'=> Auth::id(),'data'=>$traffic,'insert'=>$userTraffic], 200);
}
else return response(['status'=>false,'message'=>'traffic\'s user not found'], 404);
}
- answer:
只需使用$userTraffic->traffics()->createMany($traffic);
即可:);