1

I am building a query using db_select(); Now I need to sort my result by a field that a added using fields. Is there some nicer way than to join field_data_field_fieldname, and revision?

I was hoping for something like $query->addFieldData("field_foo", "myfoo"); so i can simply $query->orderBy('myfoo', 'asc');

I am also wondering why there is no example in the API that joins node-fields.

4

To my knowledge, db_select() isn't aware of entities or fields (fields, in the context of field that are added to nodes etc.)

I imagine you'd need to do the joins to field tables yourself. I found a little example from dbtng_example--dbtng_example.module, but as per my hunch and comments below - EntityFieldQuery is actually the only correct way to do this. Fields can define their own storage which would completely break your db_select, so...

With a bit of a performance hit (which is negligible for most) you really should do it the Drupal 7 way...

Drupal 7 now has Fields in core, and with that came the EntityFieldQuery which is a querying class for finding entities (like nodes, terms, etc) by their properties (like published status) or fields (like field_page_photo or any other fields you add via UI or otherwise)

or from API:

This class allows finding entities based on entity properties (for example, node->changed), field values, and generic entity meta data (bundle, entity type, entity id, and revision ID).

Some good examples and discussion here:

What's the proper use of EntityFieldQuery?

and I find myself referencing Do we need an EntityFieldQuery example? as well.

| improve this answer | |
  • Did it with EntityFieldQuery, works like charm! I even can directly use $query->fieldOrderBy("field_myfield", 'value', 'desc); no need to join at all. If put back the emphasis on EntityFieldQuery I'll mark your answer as… uhm… answer :) – Nils Riedemann Mar 31 '11 at 15:16
  • 2
    EntityFieldQuery is actually the only correct way to do this, because the field storage is replaceable, someone could store their fields in MongoDB. EFQ is aware of where the fields are, SelectQuery is not. – Berdir Mar 31 '11 at 17:41
  • Edited answer to reflect this and de-emphasize the direct (db_select) answer. – electblake Mar 31 '11 at 20:12

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.