To use two different databases in the same project:
1 - In your file . env put your variables of the new bank
DB_ANOTHER_HOST=localhost
DB_ANOTHER_DATABASE=banco2
DB_ANOTHER_USERNAME=root
DB_ANOTHER_PASSWORD=
2 - Now in your config/database.php add this connection:
'banco2' => [
'driver' => 'mysql',
'host' => env('DB_ANOTHER_HOST', 'localhost'),
'database' => env('DB_ANOTHER_DATABASE', 'forge'),
'username' => env('DB_ANOTHER_USERNAME', 'forge'),
'password' => env('DB_ANOTHER_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
3 - Finally in your entity file use this new connection:
class Cadastro extends Model
{
protected $connection = 'banco2';
}
4 - So the Register model will be in bank 2 and all my system will be able to account for the default bank.
5 - Last but not least, do not use your column in the main bank as foreign key, avoid using foreign keys, this is an example, always in your model do the interface:
public function Enderecos() {
return $this->hasMany(Cadastro:class, 'id', 'cadastro_id');
}
These different databases are on different servers?
– Jhonatan Simões
exactly, are even on different servers.
– geekcom
Outside the framework you can do this in Postgres ?
– gmsantos
Yes, using db_link.
– geekcom
It is impossible to define a FOREIGN KEY between tables of different databases in Postgresql, however you can define it between tables of different schemas of the same database. With db-link, or even a Foreign Data Wrapper, you can access a table from another database but cannot create an integrity restriction between them.
– anonimo