Working With Multiple Databases
Trongate v2 lets you define multiple database groups in config/database.php and access them all from any model file. No extra config. No connection juggling.
How It Works
Add groups to your config:
<?php
$databases = [
'default' => [
'host' => '127.0.0.1',
'user' => 'app',
'password' => 's3cure',
'database' => 'production'
],
'analytics' => [
'host' => 'analytics.example.com',
'user' => 'reader',
'password' => 'R3ad0nly',
'database' => 'stats'
],
'warehouse' => [
'host' => '10.0.1.50',
'user' => 'etl',
'password' => 'bulk1ns3rt',
'database' => 'dw'
]
];Each group key becomes a $this->key property in your models. The __get() method in the Model base class detects database group names and returns the right connection automatically.
Using Them
// In any model file:
$users = $this->db->get('id', 'users'); // default group
$stats = $this->analytics->get('id', 'page_views'); // analytics group
$stock = $this->warehouse->get_where(42, 'items'); // warehouse groupEach connection is lazy-loaded - no overhead for groups you don't use in a given request.
Model-Only Access
Controllers can only use the default database.
Secondary databases are model-only. This keeps the architecture clean: the controller picks the data, the model fetches it from wherever it needs to go.
Accessing a secondary database from a controller gives you the default connection instead. If you need data from multiple databases, make a model method that handles it:
// Controller - only uses default:
$report = $this->reports_model->get_sales_report($month);
// Models/reports_model.php - uses both:
public function get_sales_report(string $month): array {
$sql = "SELECT * FROM orders WHERE month = :month";
$orders = $this->db->query_bind($sql, ['month' => $month], 'object');
$sql = "SELECT * FROM events WHERE period = :period";
$events = $this->analytics->query_bind($sql, ['period' => $month], 'object');
return array_merge($orders, $events);
}Common Patterns
- Read replicas: point a group to your read-only replica and use it for reporting queries
- Analytics pipeline: keep transactional data and analytics in separate databases
- Multi-tenant: use different database groups for different tenants
- Legacy data: connect to an existing database without migrating everything at once
Need to call non-database modules from a model? See Loading Modules From Models.
We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.
Share your thoughts in the Documentation Feedback.