i'm using EntityFieldQuery to retrieve some nodes according to some conditions.

foreach (array("important", "normal") as $type) {
  $query = new EntityFieldQuery();
  $query->entityCondition("entity_type", "node")
    ->entityCondition("bundle", "Announce")
    ->fieldCondition("field_ann_cat", "value", array($nid))
    ->fieldCondition("field_ann_type", "value", array($type));
  $result = $query->execute();
  // Some actions

The first time it loops, i have my announces marked as "important" (field_ann_type). The second time it loops, i dont have any announces marked as "normal".

I've tried to intervert them, and when i have array("normal", "important") instead of array("important", "normal") in my foreach, i can see my announces marked as "normal", but not my announces marked as "important".

Does anyone knows why? Thanks.


There's no need to use a loop, if you pass an array as the 3rd argument to fieldCondition it will create an IN() statement for you in MySQL.

As far as I can tell your query should just look like this:

$types = array("important", "normal");
$query = new EntityFieldQuery();
$query->entityCondition("entity_type", "node")
  ->entityCondition("bundle", "Announce")
  ->fieldCondition("field_ann_cat", "value", $nid)
  ->fieldCondition("field_ann_type", "value", $types);

$result = $query->execute();

If you want to go one step further and ensure the IN operator is used you can pass it (but it's not necessary):

$query->fieldCondition("field_ann_type", "value", $types, 'IN');

As NenadP has already mentioned, there's no need to explicitly use an array as the 3rd argument unless you're putting the value in inline, e.g.

$query->fieldCondition("field_ann_type", "value", array("important", "normal"));`
  • In fact, i wanted them to be in multiple array (what was done in some actions commentary). By the way, i found another way to solve my problem. Thanks for the answer, i'll take a look at this later. – Lght Sep 6 '12 at 15:33
  • Gotcha. It's quite expensive to put db queries in a loop, if you can get away with grabbing all of the data in one go then using PHP to build up the local structures it's probably advisable – Clive Sep 6 '12 at 15:57

It may be because you are doing this:

->fieldCondition("field_ann_type", "value", array($type));

try just check it against $type like this:

->fieldCondition("field_ann_type", "value", $type);
  • Thinking about it there's actually no difference at all between those 2 methods...if you wrap the argument in an array the SQL statement will just convert to an IN() which is equally valid and will produce exactly the same results. – Clive Sep 6 '12 at 17:34

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.