Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Apress.Pro.Drupal.7.Development.3rd.Edition.Dec.2010.pdf
Скачиваний:
73
Добавлен:
14.03.2016
Размер:
12.64 Mб
Скачать

CHAPTER 5 WORKING WITH DATABASES

There may be queries that product duplicate results. In that case, duplicate records can be filtered out by using the distinct method.

$query

->condition('type', 'page') ->fields('n', array('title', 'changed')) ->orderBy('changed', 'DESC') ->orderBy('title', 'ASC')

->distinct();

For additional details and examples, please check out http://drupal.org/node/310069.

Inserts and Updates with drupal_write_record()

A common problem for programmers is handling inserts of new database rows and updates to existing rows. The code typically tests whether the operation is an insert or an update, then performs the appropriate operation.

Because each table that Drupal uses is described using a schema, Drupal knows what fields a table has and what the default values are for each field. By passing a keyed array of fields and values to drupal_write_record(), you can let Drupal generate and execute the SQL instead of writing it by hand.

Suppose you have a table that keeps track of your collection of giant bunnies. The schema hook for your module that describes the table looks like this:

/**

* Implements hook_schema(). */

function bunny_schema() { $schema['bunnies'] = array(

'description' => t('Stores information about giant rabbits.'), 'fields' => array(

'bid' => array( 'type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE,

'description' => t("Primary key: A unique ID for each bunny."),

),

'name' => array( 'type' => 'varchar', 'length' => 64, 'not null' => TRUE,

'description' => t("Each bunny gets a name."),

),

'tons' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE,

'description' => t('The weight of the bunny to the nearest ton.'),

),

),

98

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]