gpt4 book ai didi

php firebase api - 从嵌套文档中删除子元素

转载 作者:行者123 更新时间:2023-12-04 04:24:11 25 4
gpt4 key购买 nike

我正在使用 php sdk 从 firestore 数据库中删除一些字段,我想从文档中的数组中删除 map ,但使用的函数却删除了父数组中的所有 map 。

我的 firestore 数据库是这样的 firebase database

我想做的是从 imageUrls 数组中删除一个特定的索引 ex: index 0 及其子项,而不是其中的所有 map 。

我尝试了这两个功能:

$usersRef->update([
['path' => 'imageUrls.image_url', 'value' => FieldValue::arrayRemove(['image.png'])]
]);

还有这个

$usersRef->update([
['path' => 'imageUrls.image_url', 'value' => FieldValue::deleteField()]
]);

第一个函数删除所有 imageUrls 子元素并将 imageUrls 类型从数组更改为映射,而第二个函数什么也没发生。所有字段仍然存在于文档中,没有发生删除

<?php 

namespace App\Services;
use Google\Cloud\Firestore\FirestoreClient;
use Google\Cloud\Firestore\FieldValue;
use Google\Cloud\Firestore\FieldPath;

class FirebaseService
{
public function delete()
{
// Create the Cloud Firestore client
$db = new FirestoreClient(
['projectId' => 'MyProjectId']
);

$usersRef = $db->collection('NewStories')->document('1');

$usersRef->update(
[
['path' =>'imageUrls.image_url',
'value' => FieldValue::arrayRemove(['image.png'])]
]);
}
}

最佳答案

这可以使用 arrayRemove() 方法来实现。作为 PHP Client for Firestore

Returns a special value that can be used with set(), create() or update() that tells the server to remove the given elements from any array value that already exists on the server. All instances of each element specified will be removed from the array. If the field being modified is not already an array it will be overwritten with an empty array.


更新:

Firebase 不支持更新索引数组中的现有元素。可以在 Official Documentation 中找到更多信息。 .

解决方法:

从文档中读取整个数组,在内存中对其进行修改,然后完全更新修改后的数组字段。**

致谢 Firestore Update single item in an array field案例。

关于php firebase api - 从嵌套文档中删除子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58234768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com