如何通过PHP Datastore API获取实体的ID/Key?
How to Get Entity ID/Key with PHP Datastore API
Hey there! I totally get the frustration when you can pull all the entity properties but can't grab that ID/key—been there myself. Let's break down exactly how to fix this.
First off, the reason your attempts with $user['id'], $user['key'], or $user['__key__'] aren't working is because the entity's key isn't stored as a regular property. It's metadata attached to the entity object itself, not part of the attributes you access via array syntax.
Here's the step-by-step solution:
- First, confirm your
$useris an Entity instance: When you fetch entities vialookup()or a query, you get backGoogle\Cloud\Datastore\Entityobjects, not plain arrays. - Retrieve the Key object: Use the
key()method on your entity:$key = $user->key(); - Extract the ID or Name from the Key:
- For auto-generated numeric IDs, use the
id()method:$entityId = $key->id(); - For custom string names (if you didn't use auto-ID), use the
name()method:$entityName = $key->name(); - If you want the full path details (including the kind), use
path()which returns an array:$path = $key->path(); // Example output: ['kind' => 'User', 'id' => 12345]
- For auto-generated numeric IDs, use the
Putting it all together in a quick example:
// Assume you've already fetched your $user entity from Datastore $key = $user->key(); // Check if it's an ID-based entity if ($id = $key->id()) { echo "This entity's ID is: " . $id; } // Or if it uses a custom name if ($name = $key->name()) { echo "This entity's name is: " . $name; }
That should get you the ID/key you need without any hassle.
内容的提问来源于stack exchange,提问作者Diego Barreiro
相关产品推荐
相关产品推荐

