Eloquent mapping, is it?

Asked

Viewed 109 times

1

Is there any way to map a foreign key to a database out of my default database in Laravel Eloquent?

Example:

CREATE TABLE Banco1.Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    City int(11),

    CONSTRAINT FK_City FOREIGN KEY (City)     
      REFERENCES Banco2.City (City)     
      ON NO_ACTION    
      ON NO_ACTION
    )
);
  • And then it worked??? the answer!

1 answer

1


There must be several ways to do this, I will respond with use that I believe is the best way,

Add the second connection on to your config/database.php:

'mysql_secondary' => [
    'driver' => 'mysql',
    'host' => env('SECOND_DB_HOST', '127.0.0.1'),
    'port' => env('SECOND_DB_PORT', '3306'),
    'database' => env('SECOND_DB_DATABASE', 'database'),
    'username' => env('SECOND_DB_USERNAME', 'user'),
    'password' => env('SECOND_DB_PASSWORD', 'pass'),
    'unix_socket' => env('SECOND_DB_SOCKET', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_general_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => 'InnoDB',
],

With this you can connect to 2 banks, the default and the mysql_secondary.

To use determine which bank you are connected to just use the static method: DB::connection('mysql_secondary');, passing as parameter the name of the database connection configured in database php.

Create Migration and within the function up():

public function up()
    {
        Schema::create('Persons', function (Blueprint $table) {
            $table->increments('PersonID');
            $table->string('LastName', 255);
            $table->string('FirstName', 255);
            $table->string('Address', 255);
            $table->integer('City');
        });

        Schema::table('Persons', function($table) {
            $db = \DB::connection('mysql_secondary')->getDatabaseName();
            $table->foreign('City', 'FK_City')
            ->references('City')->on($db . '.City');            
        });
    }

This function is creating the table and right after set to FK.

OBS.: the tables must be defined as Innodb

If you wanted to, now just do the relationships belongsTo within its model.

This procedure was tested in Laravel 5.7 with PHP 7.2 and Mysql 5.7.

Reference 1, Reference 2.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.