You are here

使用drupal_write_record()进行插入和更新

老葛的Drupal培训班 Think in Drupal

程序员常遇到的一个问题,就是处理数据库中新纪录的插入和已有记录的更新。代码一般都会先检查当前的操作是一个插入操作还是一个更新操作,接着再执行合适的操作。
 
    因为Drupal所用的每个表都使用模式来描述,所Drupal知道一个表中都包含哪些字段以及每个字段的默认值。通过向drupal_write_record()传递一个包含了字段和数值的数组,那么你就可以让Drupal为你生成和执行SQL了,这样你就不需要自己手写了。
 
    假定你有一个表,用来追踪你收集的小兔子。那么你模块中的用来描述表结构的模式钩子应该是这样的:
 
/**
 * Implementation of 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.'),
            ),
        ),
        'primary key' => array('bid'),
        'indexes' => array(
            'tons' => array('tons'),
        ),
    );
 
    return $schema;
}
 
    插入一条新纪录非常方便,更新记录也是如此:
 
$table = 'bunnies';
$record = new stdClass();
$record->name = t('Bortha');
$record->tons = 2;
drupal_write_record($table, $record);
 
// The new bunny ID, $record->bid, was set by drupal_write_record()
// since $record is passed by reference.
watchdog('bunny', 'Added bunny with id %id.', array('%id' => $record->bid));
 
// Change our mind about the name.
$record->name = t('Bertha');
 
// Now update the record in the database.
// For updates we pass in the name of the table's primary key.
drupal_write_record($table, $record, 'bid');
watchdog('bunny', 'Updated bunny with id %id.', array('%id' => $record->bid));
 
    这里也支持数组,如果$record是一个数组的话,那么drupal_write_record()会在内部将其转化为一个对象。
 

Drupal版本: