Firebase PHP将映射添加到数组中

问题描述 投票:0回答:1

我正在尝试使用Firebase PHP API用地图更新/附加文档字段的数组

我在Python中有以下运行良好的代码

ref = db.collection(u'jobs').document(jobId)
                ref.update({
                        u'messages': firestore.ArrayUnion([{
                                u'category': u'0',
                                u'message': u'TEST',
                                u'sender': u'TEAM',
                                }])
                        })

尽管当我尝试在PHP中复制它时,它不起作用。我尝试了很多不同的方法来查看错误,但是得到的只是500 INTERNAL SERVER ERROR。

require 'vendor/autoload.php';
use Google\Cloud\Firestore\FirestoreClient;
use Google\Cloud\Firestore\FieldValue;
$firestore = new FirestoreClient([
    'projectId' => 'XXX-XX',
    'credentials' => 'key.json'
]);


$jobId = "XXXX";
$docRef = $firestore->collection('jobs')->document($jobId);
$docRef->update([
        'messages' => FieldValue::arrayUnion([{
            'category' : '0',
            'message' : 'TEST',
            'sender' : 'TEAM',
        }])
]);

我抬头看samples of Array Union in PHPadding data with PHP。我尝试了很多:=>arrayUnion([])arrayUnion({[]})的变体,但无济于事。

知道是什么原因造成的吗?

php firebase google-cloud-firestore google-api-php-client
1个回答
0
投票

来自Firebase Documentation

$cityRef = $db->collection('cities')->document('DC');

// Atomically add a new region to the "regions" array field.
$cityRef->update([
    ['path' => 'regions', 'value' => FieldValue::arrayUnion(['greater_virginia'])]
]);

我想你会想要这样的东西:

$docRef = $firestore->collection('jobs')->document($jobId);

// Atomically add new values to the "messages" array field. 
$docRef->update([
        ['path' => 'messages', 'value' => FieldValue::arrayUnion([{
            'category' : '0',
            'message' : 'TEST',
            'sender' : 'TEAM',
        }])
]);

0
投票

好像这里有些问题。

首先,PHP将数组用于地图和“普通”数组。 PHP中没有对象文字({})。数组值是使用=>运算符而不是:来指定的。

其次,DocumentReference::update()接受您希望更改的值列表以及路径和值。因此,更新调用将如下所示:

$docRef->update([
    ['path' => 'foo', 'value' => 'bar'
]);

您可以将DocumentReference::set()用于所需的行为。如果set()不存在,将创建一个文档;如果update()不存在,将创建一个错误。除非您指定合并行为,否则set()还将替换文档中的所有现有字段:

$docRef->set([
    'foo' => 'bar'
], ['merge' => true]);

因此,您的代码可以按以下任一方式重写:

$jobId = "XXXX";
$docRef = $firestore->collection('jobs')->document($jobId);
$docRef->set([
    'messages' => FieldValue::arrayUnion([[
        'category' => '0',
        'message' => 'TEST',
        'sender' => 'TEAM',
    ]])
], ['merge' => true]);
$jobId = "XXXX";
$docRef = $firestore->collection('jobs')->document($jobId);
$docRef->update([
    [
        'path' => 'messages', 'value' => FieldValue::arrayUnion([[
            'category' => '0',
            'message' => 'TEST',
            'sender' => 'TEAM',
        ]])
    ]
]);

最后要注意的一点:arrayUnion不会附加重复的值。因此,如果您提供的值(包括嵌套映射中的所有键和值)已经存在,则不会将其附加到文档中。

© www.soinside.com 2019 - 2024. All rights reserved.