18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

[ 209 ]<br />

Chapter 7<br />

Now look at that query again. It's returning three properties, the entity id, revision<br />

id, and bundle name. All entity queries return that same data: the entity type, entity<br />

id, revision id, and bundle. Each record is keyed by its entity id, which in turn is<br />

keyed by the entity type (since it is possible to get back multiple types of entities<br />

in a single query).<br />

Because we know exactly what that structure is, we can leverage it easily. In this<br />

case we want to fully load all artworks that we found, so we run array_keys() on<br />

the $result['artwork'] array, to get an array of just those ids and then load them.<br />

Note that we're using artwork_load_multiple(). Rather than loading each artwork<br />

separately, and running whatever queries are needed to do so, we load them all at<br />

once. That means one or five (or fifty if we were allowing that many) results all take<br />

about the same amount of time to load.<br />

Once we have our artwork objects, we simply get the render array representing each<br />

one using the functionality we build in Chapter 6 and merge them together, then<br />

return the resulting array. When it gets rendered we will see all of our artworks,<br />

one after another.<br />

Now let's make one small change to our field query:<br />

$query = new EntityFieldQuery();<br />

$query<br />

->entityCondition('entity_type', 'artwork')<br />

->propertyOrderBy('created', 'DESC')<br />

->fieldCondition('field_artist', 'value', 'Da Vinci')<br />

->range(0, 5);<br />

$result = $query->execute();<br />

Here, we also filter for just those artworks that have a field named field_artist,<br />

the value column of which is exactly equal to the string Da Vinci. The rest of the<br />

code is the same, but we will now get fewer results. If we assume that everything is<br />

stored in the local SQL database then the query could be something like this:<br />

SELECT field_data_field_artist0.entity_id AS entity_id, field_data_<br />

field_artist0.revision_id AS revision_id, field_data_field_artist0.<br />

bundle AS bundle, fcet.type AS entity_type<br />

FROM<br />

field_data_field_artist field_data_field_artist0<br />

INNER JOIN field_config_entity_type fcet ON fcet.etid = field_data_<br />

field_artist0.etid<br />

INNER JOIN artwork artwork ON artwork.aid = field_data_field_artist0.<br />

entity_id<br />

WHERE (field_data_field_artist0.field_artist_value = 'Da Vinci') AND<br />

(field_data_field_artist0.deleted = 0) AND (fcet.type = 'artwork')<br />

ORDER BY artwork.created DESC<br />

LIMIT 5 OFFSET 0

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!