2

I use this code in my module for random query:

$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'client')
->fieldCondition('field_client_enabled', 'value', 1)
->addTag('random')
->range(0, 1)
->execute;

with additional function:

function mymodule_query_random_alter($query) {
  $query->orderRandom();
}

But why I get "undefined method" error when use

$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'client')
->fieldCondition('field_client_enabled', 'value', 1)
->orderRandom() // why is this wrong?
->range(0, 1)
->execute;

?

Update:
Answer:
Found that orderRandom() is SelectQuery function, but not EntityFieldQuery

Can I simplify first code to variant without additional function?

2

Can I simplify first code to variant without additional function?

Not natively, as you've rightly said EFQ doesn't have a random order method. At a guess that's because field storage is pluggable, and it would be tricky to come up with a cross-compatible method that makes sense for e.g. MySQL and MongoDB. Might be wrong though, it may simply not have been considered important enough to implement/overlooked/etc.

If the extra step is unacceptable, the other option would be to subclass EntityFieldQuery to add your own random order method, and override the execute callback with your own version of field_sql_storage_field_storage_query() to get it into the final query.

The method you already have is arguably a bit cleaner than that; certainly it's less effort.

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.