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.

Appendix A<br />

A Merge query says, in essence, "If this record exists, update it with this query<br />

otherwise create it with this other query". The syntax for it is somewhat verbose,<br />

but it is a very powerful concept. It is most useful for setting records that may or<br />

may not exist yet, that is, merging data into the table. It can also be very useful for<br />

incrementing counters.<br />

A true merge query is atomic, that is, we're guaranteed that it will run as a single<br />

uninterrupted operation or fail completely. Since most of the databases <strong>Drupal</strong><br />

works with do not directly support Merge queries, <strong>Drupal</strong> emulates them with<br />

multiple queries and a transaction, which in most cases is close enough.<br />

The syntax should be familiar based on the other queries we've looked at already.<br />

The following example is straight out of the variable system:<br />

db_merge('variable')<br />

->key(array('name' => $name))<br />

->fields(array('value' => serialize($value)))<br />

->execute();<br />

The key() method takes an associative array of field/value pairs that are the pivot<br />

of the query. The fields() method is about the fields to set, and works the same as<br />

it does on Update or Insert queries. The above query can be read as "If there is a<br />

record where the field 'name' has the value $name, set the 'value' field. If not, insert a<br />

new record with name equal to $name and value equal to the given string." (Isn't the<br />

query above so much easier to say?)<br />

We can also define more complex logic using the insertFields() and<br />

updateFields() methods. Those work exactly like fields() but, as we<br />

might expect, apply only when taking the insert or update branches.<br />

db_merge('people')<br />

->key(array('job' => 'Speaker'))<br />

->insertFields(array(<br />

'age' => 31,<br />

'name' => 'Meredith',<br />

))<br />

->updateFields(array(<br />

'name' => 'Tiffany',<br />

))<br />

->execute();<br />

In this case, if there is already a record whose job field is "Speaker" its name field will<br />

be updated to Tiffany. If not, a new record will be created with 'job' as Speaker and<br />

'name' as Meredith. (Yes, this example is rather contrived.)<br />

[ 371 ]

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

Saved successfully!

Ooh no, something went wrong!