更新并取消设置不工作的MongoDB和Laravel

时间:2018-04-30 11:19:28

标签: mongodb laravel jenssegers-mongodb

我是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
    }
]

非常感谢任何建议,帮助和建议。

谢谢:)

1 个答案:

答案 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");
        }
    }