tomwalder / php-gds

Google Cloud Datastore Library for PHP
Apache License 2.0
164 stars 44 forks source link

creating an item with a certain ID? #149

Closed tony2001 closed 7 years ago

tony2001 commented 7 years ago

I'd like to create an entity with certain ID. In Python it's as easy as "Entity(id=123)", but I can't seem to find a way to do it in PHP GDS. From what I see, entry ID is always autogenerated, is there a way to disable it and specify ID manually?

tomwalder commented 7 years ago

IIRC, this can be done in the following way:

// Build a new entity, and set the "keyId"
$obj_book = new GDS\Entity();
$obj_book->title = 'Romeo and Juliet';
$obj_book->setKeyId('123');

// Write it to Datastore
$obj_store = new GDS\Store('Book');
$obj_store->upsert($obj_book);

However, beware that when defining your own IDs, the preference is to use Key Names.

This is because the Google random (numeric) ID algorithm does not check for duplicates against any you manually upsert. Only those it has issued itself as part of automatic inserts.

See the blue note here:

https://cloud.google.com/datastore/docs/concepts/entities#datastore-incomplete-key-php

tony2001 commented 7 years ago

Thanks a lot, that helped.