Skip to content

Creating a resource that takes data from a secondary database

jeff-h edited this page Oct 22, 2015 · 1 revision

It's trivial to create a resource which provides data to the REST API that is taken from a secondary database (for more on how Drupal can connect to multiple databases, see https://www.drupal.org/node/18429).

  1. Set up a resource that extends RestfulDataProviderDbQuery. An easy way to get started is to clone the restful_example module's watchdog resource (restful/modules/restful_example/plugins/restful/db_query/watchdog).

  2. Make sure you modify the $plugin array so it references the correct database table and table ID e.g.

$plugin = array(
...

'data_provider_options' => array(
  'table_name' => 'my_external_db_table',
  'id_column' => 'external_table_id_column_name',
),

...
);
  1. Your publicFieldsInfo fields can then reference the columns in your external database table. e.g.
public function publicFieldsInfo() {

  $public_fields['name'] = array(
    'property' => 'name_column_in_external_db_table',
  );
  1. In your RestfulSomethingResource.class.php override the getQuery() method with your own, similar to the following:
/**
 * Get a basic query object.
 *
 * @return SelectQuery
 *   A new SelectQuery object for this connection.
 */
protected function getQuery() {
  $table = $this->getTableName();
  return Database::getConnection('default', 'my_other_database')->select($table)->fields($table);
}

This will correspond to a settings.php config such as:

$databases = array (
  'default' => array (
   'default' => array (
     'driver' => 'mysql',
     'database' => 'drupal',
     'username' => 'mysqlusername',
     'password' => 'oui&^%fgso^iuhfsh99hrf',
     'host' => 'localhost',
     'port' => '',
     'prefix' => '',
   ),
  ),
  'my_other_database' => array (
   'default' => array (
     'driver' => 'mysql',
     'database' => 'my_other_database',
     'username' => 'mysqlusername',
     'password' => 'oui&^%fgso^iuhfsh99hrf',
     'host' => 'localhost',
     'port' => '',
     'prefix' => '',
   ),
  ),
);
Clone this wiki locally