使用Laravel时如何删除MongoDb json中的属性

时间:2018-10-23 06:11:46

标签: php mongodb laravel

我想在MongoDb中修复某些问题,并且需要快速添加属性。

我使用add方法快速地做到了这一点。

现在,我要修复和删除一些属性。

如您所见,通过使用isset($department[$arr['attribute']]),我将知道该属性是否存在。

如果该属性存在,则设置空值$department[$arr['attribute']] = '';,然后使用unset方法unset($department[$arr['attribute']]);

remove方法不起作用。

有什么想法吗?

<?php


namespace App\Http\Controllers\Api;

use App\Department;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class FixController extends Controller
{

    protected $concept;

    /**
     * DepartmentController constructor.
     */
    public function __construct()
    {
        $this->middleware(
            function ($request, $next) {
                $this->concept = Auth::user()->current_desk_artifacts[0];
                return $next($request);
            }
        );
    }

    public function add($attribute, $value)
    {

        $counter = 0;

        $arr = [
            'attribute' => $attribute,
            'value' => $value,
            'counter' => &$counter
        ];

        Department::chunk(
            100,
            function ($departments) use ($arr) {
                print_r($arr);
                echo '<br/>';
                foreach ($departments as $department) {
                    if (
                    !isset($department[$arr['attribute']])
                    ) {
                        $department[$arr['attribute']] = $arr['value'];
                        $department->save();
                        $arr['counter']++;
                        echo $arr['counter'];
                        echo '<br/>';
                    }
                }
            }
        );

    }

    public function remove($attribute, $value)
    {

        $counter = 0;

        $arr = [
            'attribute' => $attribute,
            'value' => $value,
            'counter' => &$counter
        ];

        Department::chunk(
            100,
            function ($departments) use ($arr) {
                print_r($arr);
                echo '<br/>';
                foreach ($departments as $department) {
                    if (
                    isset($department[$arr['attribute']])
                    ) {
                        $department[$arr['attribute']] = '';
                        unset($department[$arr['attribute']]);
                        $department->save();
                        $arr['counter']++;
                        echo $arr['counter'];
                        echo '<br/>';
                    }
                }
            }
        );

    }

}

0 个答案:

没有答案