我遇到一种情况,我需要查询一些节点并连接附加到该节点的两个字段。这两个字段都可以有无限的值,因此字段表中有多行。我试图让它返回 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 条记录,而实际上还有更多记录。
然后我尝试尝试模块 EntityFieldQuery Extra Fields
$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
返回的所有结果才能获取我需要的字段,这会对性能造成巨大影响。
最佳答案
->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) {
// ...
}
关于mysql - Drupal 7 带连接的选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33574133/