I'm a little confused by how the node data is stored in the database. It seems like the title is stored in the db "node," while the body is stashed field_data_body, and custom fields are placed elsewhere.

I have create a custom module that pulls certain pieces of content, but I need to match up the title with the body. I've been successful pulling my list of titles:

    function foo() {
      $query = db_select('node', 'n')
       ->fields('n', array('type','title', 'nid'))
       ->condition('type', 'fooBar')
          return $query;
        foreach ($result as $node) {
         $id = $node->nid;

How can I match each of these with their bodies?

Thanks! -JB


If you want directly include the body within your result set, you can do a join on the field_data_body table.

$query = db_select('node', 'n');

$query->leftJoin('field_data_body', 'd', '(d.entity_id = n.nid AND d.entity_type = :node)', array(':node' => 'node'));

    ->fields('n', array('type', 'title', 'nid'))
    ->fields('d', array('body_value', 'body_summary', 'body_format'))
    ->condition('type', 'fooBar')
    ->condition('status', 1)

You are correct - Drupal stores the data for fields inside of separate tables. Depending on your use case, you may find it easier to use node_load() which will load the entire node object with all the field data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.