entity query
Class based method (recommended)
1234567891011121314151617181920212223// 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 topublic 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();}Static method (not recommended)
1$query = \Drupal::entityQuery('node');
entity load
Class method (recommended)
1234567891011121314151617181920protected $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,];}Static method (not recommended)
12345// Get a node storage object.$node_storage = \Drupal::entityManager()->getStorage('node');// Load a single node.$node_storage->load($nid);Global method (not recommended)
12// Load a single entity.$node = entity_load('node', $nid);special class method
1$node = Node::load($nid);
field update
simple field
12$title_field = $node->get('title');$title_field->value = 'title changed';complex field
更新第n条记录的任意字段
1234$body_field = $node->get('body');$values = $body_field->getValue();$values[0]['summary'] = 'first way summary';$body_field->setValue($values);只更新第一条记录的话,像simple field一样更新
12$body_field = $node->get('body');$body_field->summary = 'another way summary';
参考资料
Entity Query cheatsheet
Entity queries and loading entities
Loading and editing fields