2011-05-16 11 views
8

¿Hay alguna manera más óptima y más corta de obtener nodos con ciertas condiciones?EntityFieldQuery múltiples condiciones alternativas

$query = new EntityFieldQuery; 
$result = $query 
    ->entityCondition('entity_type', 'node') 
    ->propertyCondition('type', $node_type) 
    ->propertyCondition('title', $title) 
    ->fieldCondition('field_number', 'value', '1', '='); 
    ->propertyCondition('status', 1, '=') 
    ->execute(); 

// $result['node'] contains a list of nids where the title matches 
if (!empty($result['node']) { 
    // You could use node_load_multiple() instead of entity_load() for nodes 
    $nodes = entity_load('node', array_keys($result['node'])); 
} 

$query_two = new EntityFieldQuery; 
$result_two = $query_two 
    ->entityCondition('entity_type', 'node') 
    ->propertyCondition('type', $node_type) 
    ->propertyCondition('title', $title) 
    ->fieldCondition('field_number', 'value', '2', '='); 
    ->propertyCondition('status', 1, '=') 
    ->execute(); 

// $result_two['node'] contains a list of nids where the title matches 
if (!empty($result_two['node']) { 
    // You could use node_load_multiple() instead of entity_load() for nodes 
    $nodes_two = entity_load('node', array_keys($result_two['node'])); 
} 

Respuesta

13

Bueno, ciertamente podría utilizar ->fieldCondition('field_number', 'value', array(1, 2)), pero aparte de eso, no que yo sepa (y escribí EntityFieldQuery). Incluso si tuviera que volver a escribir esto en una consulta de almacenamiento SQL, no sería mucho más simple.

No necesita especificar = como el operador y tampoco necesita especificar IN, son valores predeterminados para un valor escalar/matriz.

+0

Gracias por tomarse el tiempo para responder a esta pregunta y gracias por EFQ, es una característica increíble. – Sam152

1

Recientemente escribí un contenedor para EntityFieldQuery, ya que solo lo uso demasiado. Entonces la forma en que lo llamo se convierte en, el resultado puede ser una identificación o una matriz de identificadores. Espero que esto tenga sentido.

$ids = qplot_api_find_nodes2(
    array(
     'type' => 'content', 
     'field_content_project' => array('target_id', 10, '='), 
    ), 
    array(
     'created' => 'ASC' 
    ), 
    TRUE 
); 

/** 
* Returns node nid(s) with filters and sorts. 
* 
* @param array $conds 
* Condition entries, there're three different type of conditions 
* 1. prefixed with entity_, ex. 'entity_type' => 'node' 
* 2. prefixed with field_, ex. 'field_project', 
*  two formats allowed, simple version 'field_tag' => 'abc', 
*  or long version, 'field_tag' => array('target_id', 11, '=') 
* 3. no prefix or other prefix, 'title' => 'abc' 
* Default $conds contains 'entity_type' => 'node' entry. 
* 
* @param array $sorts 
* Sort entiries, there're two different type of sorts 
* 1. prefixed with field_, ex. 'field_tag' => array('target_id', 'ASC') 
* 2. no prefix or other prefix, 'title' => 'ASC' 
* Default $sorts are empty 
* 
* @param bool $all 
* If all matching nid are returned, or just the first one, default FALSE 
* 
* @return int 
* The nid for the supplied id or 0 if not found. 
* Or array of nids if $all = TRUE 
* 
* @author Fang Jin <[email protected]> 
*/ 
function qplot_api_find_nodes2($conds, $sorts = NULL, $all = FALSE) { 
    $conds = array_merge(array('entity_type' => 'node'), $conds); 
    if (empty($sorts)) { 
     $sorts = array(); 
    } 

    $query = new EntityFieldQuery(); 

    // apply condition to query 
    foreach ($conds as $key => $value) { 
     $splits = explode('_', $key); 
     $type = $splits[0]; 
     if (count($splits) == 1) { 
      $type = 'property'; 
     } 

     switch ($type) { 
      case 'entity': 
      $query->entityCondition($key, $value); 
      break; 

      case 'field': 
      if (is_array($value)) { 
       $property = isset($value[1]) ? $value[0] : 'value'; 
       $assigned = isset($value[1]) ? $value[1] : $value[0]; 
       $operator = isset($value[2]) ? $value[2] : '='; 
       $query->fieldCondition($key, $property, $assigned, $operator); 
      } else { 
       $query->fieldCondition($key, 'value', $value); 
      } 
      break; 

      // rest of them are all property 
      default: 
      $query->propertyCondition($key, $value); 
      break; 
     } 
    } 

    // apply sort to query 
    foreach ($sorts as $key => $value) { 
     $splits = explode('_', $key); 
     $type = $splits[0]; 
     if (count($splits) == 1) { 
      $type = 'property'; 
     } 

     switch ($type) { 
      case 'field': 
      $query->fieldOrderBy($key, $value[0], $value[1]); 
      break; 

      default: 
      $query->propertyOrderBy($key, $value); 
      break; 
     } 
    } 

    $result = $query->execute(); 
    $ctype = $conds['entity_type']; 
    if (!empty($result[$ctype])) { 
     $keys = array_keys($result[$ctype]); 
     if ($all) { 
      return $keys; 
     } 
     else { 
      return $keys[0]; 
     } 
    } else { 
     if ($all) { 
      return array(); 
     } else { 
      return 0; 
     } 
    } 
} 
Cuestiones relacionadas