1

Estou tentando criar uma migration que possui uma chave estrangeira referenciando o id de uma tabela de outro banco, ambos MySQL.

Segue o código:

//config/database.php
'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
        'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB2_HOST', '127.0.0.1'),
            'port' => env('DB2_PORT', '3306'),
            'database' => env('DB2_DATABASE', 'forge'),
            'username' => env('DB2_USERNAME', 'forge'),
            'password' => env('DB2_PASSWORD', ''),
            'unix_socket' => env('DB2_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],


// migration
Schema::create('customer_partner', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
    $table->integer('partner_id')->unsigned();
    $table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
    $table->integer('customer_id')->unsigned();
    $table->foreign('customer_id')->references('id')->on(env('DB2_DATABASE').'.clients');
});

Porém ao executar o comando php artisan migrate ocorre o seguinte erro:

[Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `customer_partner` add constraint `customer_partner_customer_id_foreign` foreign key (`customer_id`) references `banco2`.`clients` (`id`))

[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

Alguma ideia do que posso estar fazendo errado?

3
  • banco2.clients (id) é INT UNSIGNED?
    – juniorb2ss
    21/06/2017 às 12:34
  • Ajudaria bastante se você nos mostrasse o SQL/Blueprint que define o relacionamento entre os bancos.
    – FReNeTiC
    21/06/2017 às 13:13
  • Puxa vida! Verifiquei o tipo da coluna id da tabela banco2.clients e estava mediumint. Alterei o código da migration para $table->mediumInteger('customer_id')->unsigned(); e funcionou! Muito obrigado @juniorb2ss e @FReNeTic pela ajuda. 21/06/2017 às 14:27

0

Você deve fazer log-in para responder a esta pergunta.

Pesquise outras perguntas com a tag .