任何人都可以告诉我如何使用其 id 更新 firestore 文档吗?我可以使用 kreait 的 laravel-firebase 包创建一个文档并更新它。
我的下面的代码在 firestore 上创建文档。但是,如何使用文档引用或 ID 更新同一文档。
$groupsRef = app('firebase.firestore')->database()->collection('groups');
$groupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $image,
'groupId' => '',
'groupMembers' => [
auth()->user()->id."_".auth()->user()->name
],
'groupName' => $request->group_name,
'recentMessage' => '',
'recentMessageSender' => '',
'recentMessageTime' => ''
];
$groupsRef->add($groupData);
下面的实现使用其名称而不是其引用来更新文档。
$document = $groupsRef->document($request->group_name);
$groupId = $document->id();
$updatedGroupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $request->hasFile('groupIcon') ? $image : '',
'groupId' => $groupId,
'groupMembers' => [
auth()->user()->id."_".auth()->user()->name
],
'groupName' => $request->group_name,
'recentMessage' => '',
'recentMessageSender' => '',
'recentMessageTime' => ''
];
$updatedFitfam = $document->update($updatedGroupData);
Firestore add 返回文档引用,您可以从中获取文档 ID。然后更新如下:
$groupsRef = app('firebase.firestore')->database()->collection('groups');
$groupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $image,
'groupId' => '',
'groupMembers' => [
auth()->user()->id."_".auth()->user()->name
],
'groupName' => $request->group_name,
'recentMessage' => '',
'recentMessageSender' => '',
'recentMessageTime' => ''
];
$docId = $groupsRef->add($groupData);
$updatedGroupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $request->hasFile('groupIcon') ? $image : '',
'groupId' => $groupId,
'groupMembers' => [
auth()->user()->id."_".auth()->user()->name
],
'groupName' => $request->group_name,
'recentMessage' => '',
'recentMessageSender' => '',
'recentMessageTime' => ''
];
$updatedFitfam = $document->update($docId->id());
如果您想使用
$groupsRef
从 $request->group_name
获取文档,请使用以下解决方法:
$groupsRef = app('firebase.firestore')->database()->collection('groups');
$document = $groupsRef->document($request->group_name);
$snapshot = $document->get();
if ($snapshot->exists()) {
$existingData = $snapshot->data();
$updatedGroupData = [
'groupAdmin' => auth()->user()->id."_".auth()->user()->name,
'groupDescription' => $request->group_description,
'groupIcon' => $request->hasFile('groupIcon') ? $image : '',
'groupMembers' => array_merge(
$existingData['groupMembers'] ?? [],
[auth()->user()->id."_".auth()->user()->name]
),
'recentMessage' => $existingData['recentMessage'] ?? ' ',
'recentMessageSender' => $existingData['recentMessageSender'] ?? ' ',
'recentMessageTime' => $existingData['recentMessageTime'] ?? ' '
];
$document->update($updatedGroupData);
}
参考此docs