[Drupal] Why we use only entity and entity field query except db_select in Drupal

| | 2 min read

While working with entity, I always had a doubt as to why we use Entity and Entity Field query except Db_select() in Drupal. It is a great and fast way to organize and extract our data in Drupal sites. Here are a few more points to support these concepts :

If you want to know how to create custom entity, please go through the overview over here.

  • Entity is something like normal table relations with a foreign key concept and a great way to organize your data in Drupal. It is an object or instance of a base or extended class. Nodes, comments taxonomy terms etc constitute entity types.
  • To acquire data of an entity, we can use entity_load(). This helps us to improve our code. Entities enable us to focus on the important functionality that is specific to our data type. So we can create our own entity (custom) for structured or related data in Drupal. The data wrappers in entity make use of the available information to provide a simple and unified access to entities and their properties.
  • For getting a specific field data from an entity, we can use 'EntityFieldQuery' concept instead of normal drupal db_select() which improves loose coupling and is more flexible. This is because it is quite simple. For example, for db_select() we need to use:
    
      $nids = db_select('node', 'n')
         ->fields('n', array('nid'))
         ->join('field_data_field_sample', 'sample', 'sample.entity_id = n.nid')
         ->condition('n.type', 'sample_bundle_type')
         ->condition('sample.field_sample_value', $val)
         ->execute()->fetchCol();
    

    In EntityFieldQuery we can use:

    
      $query = new EntityFieldQuery;
      $entities = $query->entityCondition('entity_type', 'node')
         ->entityCondition('bundle', 'sample_bundle_type')
         ->fieldCondition('field_sample', 'value', $val)
         ->execute();
      if (!empty($entities['node'])) {
        $nodes = entity_load('node', array_keys($entities['node']));
      } else {
        $nodes = array();
      }
    
  • However, please note that entity concepts are good if there is a featured concept, i.e., the data should be large, related and structured so that we can make fields for the entity. For simple one, normal tables and db_select() is more useful.

Please feel free to share your thoughts and queries.

For further assistance, click here.