You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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 $user is an Entity instance: When you fetch entities via lookup() or a query, you get back Google\Cloud\Datastore\Entity objects, 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]
      

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:57:09