我是MongoDB
的新手,我正在使用jenssegers/laravel-mongodb
包来构建API。
我在更新和删除数组中的记录时遇到问题。
以下是使用foreach
的更新代码foreach ($event->volunteers as $key => $volunteer) {
if ($volunteer['user_id'] == $request->user_id) {
$event->where('volunteers.user_id', $request->user_id)
->update(["volunteers.$key.attendance_status" => $request->attendance_status
]);
}
}
以下是与Pull
相同的代码 Event::where('volunteers.user_id', $request->user_id)->push('volunteers', [
'attendance_status' => $request->attendance_status
], true);
这是未设置的代码
foreach ($event->volunteers as $key => $volunteer) {
if ($volunteer['user_id'] == $request->user_id) {
$event->where('volunteers.user_id', $request->user_id)
->unset(
"volunteers.$key.attendance_status");
}
}
他们都没有工作
我的数据库结构是
"volunteers" : [
{
"user_id" : NumberInt(1),
"name" : "Prafful K Panwar",
"skills" : [
"Plumber",
"Carpenter"
],
"incentives" : {
"tshirt_size" : "XXL"
},
"ready_to_contribute_min_amount" : "Yes",
"attendance_status" : false
},
{
"user_id" : NumberInt(2),
"name" : "Prafful Panwar",
"skills" : [
"Plumber"
],
"incentives" : {
"tshirt_size" : "XXL"
},
"ready_to_contribute_min_amount" : "Yes",
"attendance_status" : false
}
]
非常感谢任何建议,帮助和建议。
谢谢:)
答案 0 :(得分:0)
将提取代码更改为
Event::where('volunteers.user_id', $request->input('user_id'))->push('volunteers', ['attendance_status' => $request->input('attendance_status') ], true);
将未设置的代码更改为
$userId = $request->input('user_id'); foreach ($event->volunteers as $key => $volunteer) { if ($volunteer['user_id'] == $userId) { $event->where('volunteers.user_id', $userId) ->unset("volunteers.$key.attendance_status"); } }