I'm using EntityFieldQuery to pull nodes based on a flag created with the Flag module (3.2):

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'article')
    ->propertyCondition('status', 1)
    ->range(0, 25)
    ->addMetaData('flag_name_value', 'my_flag_name');

I'm not seeing the flagging table being joined to the query (from the error being thrown):

Unknown column 'flagging.fid' in 'on clause': 
SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, 'node' AS entity_type FROM node node INNER JOIN flag f ON flagging.fid = f.fid WHERE (node.status = 1) AND (node.type = 'article') AND (f.name = 'my_flag_name') LIMIT 25 OFFSET 0

Below is the flag_query_flagging_flag_names_alter from the flag module file:

function flag_query_flagging_flag_names_alter(QueryAlterableInterface $query) {
  // Get value and operator for bundle condition from meta data.
  $value = $query->getMetaData('flag_name_value');
  $operator = $query->getMetaData('flag_name_operator');
  // Join [flag] and [flagging] tables by [fid] and
  // apply bundle condition on [flag].[name] field.
  $query->join('flag', 'f', 'flagging.fid = f.fid');
  $query->condition('f.name', $value, $operator);

What am I missing in the query build to join the flagging table?

2 Answers 2


The flagging table is not available when querying for nodes using an EntityFieldQuery, that's why the flagging.fid column is missing in this query.

In order to get hold of flaged items, the flagging-entities need to be queried instead:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'flagging')
  ->entityCondition('bundle', 'name_of_some_flag');

Then use entity_load('flagging', ...) and obtain the nid from the entity_id-property of the flagging entities.

However keep in mind that it is impossible to sort / filter on properties of the target object (nodes in this case) because EntityFieldQuery does not support JOINs in Drupal 7.

I suggest to build a view instead of trying to battle the EFQ in this particular case.


To get all flagged entities on Drupal 8, plus a condition on the type (here on the type of Node) :

use Drupal\Core\Database\Database;

$connection = Database::getConnection();

$query = $connection->select('flagging', 'f');
$query->join('node_field_data', 'n', 'n.nid = f.entity_id');
$query->fields('f', ['entity_id', 'entity_type', 'flag_id', 'global'])
  ->fields('n', ['nid', 'type'])
  ->condition('f.flag_id', 'bookmark') // replace by flag machine name
  ->condition('n.type', 'article'); // replace by content type name

$data = $query->execute();
$results = $data->fetchAll(\PDO::FETCH_OBJ);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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