怎么通过 API 取得 Entity 对象?
发布于
需要在自定义页面显示指定节点和用户的信息,请问怎么从数据库里取得相应的数据?
1 个回答
参考官方 Entity API 文档,可以通过以下多种方式加载节点、用户及其它 Entity 对象。
// Using the storage controller (recommended).
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load(1);
// Use the static method
$node = Node::load(1);
// Load multiple entities, also exists as entity_load_multiple().
$entities = \Drupal::entityTypeManager()->getStorage($entity_type)->loadMultiple([1, 2, 3]);
// Load entities by their property values.
$entities = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'article']);
注意应避免使用 Entity::load()
形式进行加载 Entity,而使用 \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id)
。这样可以降低代码耦合性从而更易于进行单元测试。