Firestore:所提供的数组中不存在密钥写入



有人能告诉我以下错误消息试图告诉我什么吗?

致命错误:未捕获异常"InvalidArgumentException"消息"所提供的数组中不存在密钥写入。"在里面/vendor/google/cloud/Core/src/ArrayTrait.php:38

Stack trace: 
#0 /vendor/google/cloud/Firestore/src/Connection/Grpc.php(127): GoogleCloudFirestoreConnectionGrpc->pluck('writes', Array) 
#1 /vendor/google/cloud/Firestore/src/WriteBatch.php(381): GoogleCloudFirestoreConnectionGrpc->commit(Array) 
#2 import.php(45): GoogleCloudFirestoreWriteBatch->commit() 
#3 {main} thrown in /vendor/google/cloud/Core/src/ArrayTrait.php on line 38

我的代码看起来像:

$batch = $project->db->batch();
foreach($memberList as $member){
$addedDocRef = $collection->newDocument();
$data["id"] = $addedDocRef->id();
$data["creation"] = $this->generateCreation();
$data["publication"] = $this->generatePublication();    
$batch->create($addedDocRef, $data);
}
$batch->commit();

它告诉您正在运行提交,但批处理不包含任何操作。可能当$memberList为空时,会显示此错误。防止错误的一个简单方法是:

if (! empty($memberList)) {
$batch->commit();
}

另外,你确定$batch->create((存在吗?您应该使用set((方法。这是最新的消防仓库文档:

$batch = $db->batch();
# Set the data for NYC
$nycRef = $db->collection('cities')->document('NYC');
$batch->set($nycRef, [
'name' => 'New York City'
]);
# Update the population for SF
$sfRef = $db->collection('cities')->document('SF');
$batch->update($sfRef, [
['path' => 'population', 'value' => 1000000]
]);
# Delete LA
$laRef = $db->collection('cities')->document('LA');
$batch->delete($laRef);
# Commit the batch
$batch->commit();

Alexander的回答对于特定情况是正确的。

更通用的解决方案是使用Firestore中直接提供的函数,该函数检查是否有任何东西被排入队列进行批处理。

if (!$batch->isEmpty()) {
$batch->commit();
}

来源:https://github.com/googleapis/google-cloud-php-firestore/blob/master/src/WriteBatch.php#L483

最新更新