Entity queries , loading entities , editing fields

entity query

  1. Class based method (recommended)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    // This function and the next are part of the dependency injection pattern. We will explain those in future chapters.
    public function __construct(QueryFactory $entity_query) {
    $this->entity_query = $entity_query;
    }
    public static function create(ContainerInterface $container) {
    return new static(
    // User the $container to get a query factory object. This object lets us create query objects.
    $container->get('entity.query')
    );
    }
    // This function shows how to
    public function myCallback() {
    // Use the factory to create a query object for node entities.
    $query = $this->entity_query->get('node');
    // Add a filter (published).
    $query->condition('status', 1);
    // Run the query.
    $nids = $query->execute();
    }
  2. Static method (not recommended)

    1
    $query = \Drupal::entityQuery('node');

entity load

  1. Class method (recommended)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    protected $entity_manager;
    public function __construct(EntityTypeManagerInterface $entity_manager) {
    $this->entity_manager = $entity_manager;
    }
    public static function create(ContainerInterface $container) {
    return new static(
    $container->get('entity_type.manager')
    );
    }
    public function load() {
    $node_storage = $this->entity_manager->getStorage('node');
    $nid = 1;
    $node = $node_storage->load($nid);
    return [
    '#markup' => $node->get('title')->value,
    ];
    }
  2. Static method (not recommended)

    1
    2
    3
    4
    5
    // Get a node storage object.
    $node_storage = \Drupal::entityManager()->getStorage('node');
    // Load a single node.
    $node_storage->load($nid);
  3. Global method (not recommended)

    1
    2
    // Load a single entity.
    $node = entity_load('node', $nid);
  4. special class method

    1
    $node = Node::load($nid);

field update

  1. simple field

    1
    2
    $title_field = $node->get('title');
    $title_field->value = 'title changed';
  2. complex field

    • 更新第n条记录的任意字段

      1
      2
      3
      4
      $body_field = $node->get('body');
      $values = $body_field->getValue();
      $values[0]['summary'] = 'first way summary';
      $body_field->setValue($values);
    • 只更新第一条记录的话,像simple field一样更新

      1
      2
      $body_field = $node->get('body');
      $body_field->summary = 'another way summary';

参考资料

Entity Query cheatsheet
Entity queries and loading entities
Loading and editing fields