Drupal Helpful codes for database queries

March 18, 2018

Being a drupal user from last around 5 years, I used to know small codes for drupal. These codes helps in many ways, in templating, or in writing custom automation etc.

To get all the Node Id's (nid) from a content type

$query = db_select( 'node', 'n' );
  $query
    ->condition( 'n.type', '' )
    ->fields('n', array('nid'));
  $result = $query
     ->execute()
   ->fetchAll();

foreach( $result as $row ) { print_r($row); }

To get all the Node Id's and Titles from a content type

$query = db_select( 'node', 'n' );
  $query
    ->condition( 'n.type', '' )
    ->fields('n', array('nid', 'title'));
  $result = $query
    ->execute()
   ->fetchAll();

foreach( $result as $row ) { print_r($row); }

To get Node title from a single Node without loading the node

Note: You can get all the attributes from a node by loading a node, by using php code: node_load(nid). But, it is very heavy operation. In many cases, you do not want to load complete node.

function getTitle($nid) {
  $query = db_select( 'node', 'n' );
  $query
      ->condition( 'n.nid', $nid)
      ->fields('n', array('title'));
    $result = $query->execute();
    
    return $result->fetchObject()->title;
}

To get random nodes from a content type and fetch only node id and title, and do not fetch all nodes

  $contentType = 'article';
  $rangeFrom = 0;
  $number = 4;
  $query = db_select('node', 'n');
      $query->condition('n.status', NODE_PUBLISHED);
      $query->condition('n.type', $contentType);

  $info = $query
  ->fields('n', array('nid', 'title'))
    ->orderBy('n.changed', 'DESC')
    ->range($rangeFrom, $number)
    ->execute()
    ->fetchAll();
print_r($info);

Get a node based on a field value

Example: If my content type has a field: videoId. Find out if this content type has any node with this particular videoIdas value.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'my_content_type')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('my_field_name', 'value', 'my_required_field_value', '=');

$result = $query->execute();

print_r($result);

Similar Posts

Latest Posts