Working With Multiple Databases
Trongate v2 makes it simple to work with multiple databases. Model files automatically have access to all database groups defined in config/database.php. This allows you to query, update, and insert data across different databases with ease.
Database Access Across Multiple Groups
Any database group defined in config/database.php is ready to use immediately. You do not need to explicitly load a connection:
Notice how you can work with multiple databases by referencing the database object assigned to each group (e.g., $this->db, $this->analytics, $this->warehouse).
Calling Modules From Model Files (Edge Case)
Sometimes your models may also need to call other modules — for example, to send emails, process files, or call external APIs. Trongate handles this explicitly with :
Heads up: Calling other modules from inside model files is an edge case. Most of the time, your models will just work with databases.
Only use $this->module() when you are calling modules from within model files.
Complete Example: Combining Multiple Databases and Modules
Here’s a realistic example where a model works across multiple databases and calls other modules:
This example demonstrates:
- Working with multiple database groups automatically (
$this->db,$this->analytics) - Calling modules explicitly for non-database tasks (
$this->tax,$this->email_sender)
Common Use Cases in Multi-Database Models
- Processing orders where transactional data and analytics live in different databases
- Sending emails after database updates
- Performing calculations that reside in separate modules
- Logging or auditing actions across multiple data stores
- Calling external APIs that rely on database data
Controller vs Model Distinction
Controllers can automatically load modules, while models require explicit $this->module() calls. This ensures a clear distinction:
- Load modules at the start of model methods for clarity
- Database connections never require
module() - If a module isn’t loaded, v2 will produce a helpful error message
- Keep models focused on data operations across multiple databases
- Use controllers for orchestrating complex workflows