morrislaptop / firestore-php

Firestore SDK for PHP without gRPC
MIT License
67 stars 31 forks source link

Update Collection Attribute #23

Open ronlinet opened 3 years ago

ronlinet commented 3 years ago

The bellow code is updating the 'alert_notification' User attribute but deleting all other fields. What is the correct approach to update a collection element without destroying all other fields?

$this->firestoreServiceAccount = ServiceAccount::fromJsonFile( storage_path()  . '/app/google-services.json');
        $this->firestore = (new Factory)->withServiceAccount($this->firestoreServiceAccount)->createFirestore();

            $collection     = $this->firestore->collection('users')->document( (int) $user->id );
            $collection->set
            (
                [
                    'alert_notifications'             => $user->alert_notifications,
                ]
            ); 
ronlinet commented 3 years ago

Simply recreating all collection with updated attribute does the trick. Working code :

$this->firestoreServiceAccount = ServiceAccount::fromJsonFile( storage_path()  . '/app/google-services.json');
        $this->firestore = (new Factory)->withServiceAccount($this->firestoreServiceAccount)->createFirestore();

            $collection     = $this->firestore->collection('users')->document( (int) $user->id );

            $email                   = $collection->snapshot()->data()['email'];
            $fcm_registration_token  = $collection->snapshot()->data()['fcm_registration_token'];

            $collection->set
            (
                [
                    'fcm_registration_token' => $fcm_registration_token,
                    'email'                 => $email,
                    'alert_notifications'   => $user->alert_notifications,
                ]
            );            
ronlinet commented 3 years ago

@morrislaptop should we check the Update feature checkbox in the library TODO list and include the above code in the demo code ?