使用另一个数组更新文档中的数组字段

时间:2019-05-07 13:15:22

标签: laravel mongodb jenssegers-mongodb

在带有MongoDB和jenssegers的Laravel 5中,我试图更新文档的Array字段。但这不是更新。

当字段包含Array [2]时,我正在尝试使用Array [1]更新它,但未更新。 另一方面,另一个文档字段正在正确更新。

我检查了情况:

old value | new value | result
---------------------------------
Array(1)  | Array(2)  | OK
---------------------------------
Array(1)  | null      | OK
---------------------------------
Array(1)  | Array(0)  | OK
---------------------------------
Array(2)  | Array(1)  | NO UPDATE

我的文档如下:

{
    "name": "test",
    "default": 0,
    "variables": [
        {
            "name": "responsibilities",
            "type": "text"
        },
        {
            "name": "requirements",
            "type": "text"
        }
    ]
}

还有我的PHP代码(我现在已经以这种方式处理了,但是一点都不优雅)。我想念什么?

$document->name = $name;
$document->default = $default;
$document->variables = [];  // there is neccesity to clear this field first, because overriding with smaller array
$document->save();          // is faulty (for ex. when removing one variable)
$document->variables = $variables;
$document->save();

0 个答案:

没有答案
相关问题