Drupal 7选择带连接的查询

时间:2015-11-06 19:20:33

标签: mysql drupal

我有一种情况,我需要查询一些节点并加入连接到节点的两个字段。这两个字段都可以具有无限值,因此字段表中有多行。我试图让它返回nid和为字段找到的所有值记录。

  $query = db_select('node', 'n');
  $query->leftJoin('field_data_aaa_alert_path', 'ap', 'n.nid = ap.entity_id');
  $query->leftJoin('field_data_aaa_alert_region', 'ar', 'n.nid = ar.entity_id');
  $query
    ->fields('n', array('nid'))
    ->fields('ap', array('aaa_alert_path_value'))
    ->fields('ar', array('aaa_alert_region_value'))
    ->groupBy('n.nid')
    ->condition('type', 'aaa_alert')
    ->condition('status', 1)
    ->orderBy('created', 'DESC');

  $result = $query->execute();
  while($record = $result->fetchAssoc()){
    //...
  }

这样可行,但实际上只有aaa_alert_path_value和aaa_alert_region_value会返回1条记录。

然后我尝试尝试模块the jsfiddle when it's commented out

    $query = new EntityFieldQueryExtraFields();
    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'aaa_alert')
        ->propertyCondition('status', NODE_PUBLISHED)
        ->addExtraField('aaa_alert_region', 'value')
        ->addExtraField('aaa_alert_path', 'value')
        ->propertyOrderBy('created', 'DESC');

    $result = $query->execute();

这可以并且将返回我需要的两个字段的所有记录,但是如果两个字段中的一个不包含记录,则此模块中存在一个不会返回任何内容的错误。

我尝试过使用不同的连接,但我似乎无法正确使用它。我在这里错过了什么?我试图在不使用EntityFieldQuery类的情况下执行此操作,因为它需要node_load返回所有返回的结果以获取我需要的字段,这是一个巨大的性能损失。

1 个答案:

答案 0 :(得分:0)

->groupBy('n.nid')

存在问题

groupBy方法正在做的是将具有相似节点ID的所有记录合并到一个结果中。删除它将允许每个节点ID的多个结果。请注意,在while循环中,每个字段值将作为单独的记录返回。如果要将每个节点组合成一个数组,可以执行以下操作:

<?php

$query = db_select('node', 'n');
$query->leftJoin('field_data_aaa_alert_path', 'ap', 'n.nid = ap.entity_id');
$query->leftJoin('field_data_aaa_alert_region', 'ar', 'n.nid = ar.entity_id');
$query
  ->fields('n', array('nid'))
  ->fields('ap', array('aaa_alert_path_value'))
  ->fields('ar', array('aaa_alert_region_value'))
  ->condition('type', 'aaa_alert')
  ->condition('status', 1)
  ->orderBy('created', 'DESC');

$result = $query->execute();
while($record = $result->fetchAssoc()){
  $nid = $result['nid'];
  $grouped[$nid][] = $record;
}

foreach($grouped as $nid => $value) {
  // ...
}
相关问题