简体   繁体   English

如何在 Laravel 迁移中使用多个数据库设置外键约束

[英]How do you set Foreign Key Constraint in Laravel Migration using Multiple Databases

I'm currently working on a project that requires using multiple databases.我目前正在做一个需要使用多个数据库的项目。 In my .env file I have the following database variables:在我的 .env 文件中,我有以下数据库变量:

DB_CONNECTION=mysql
DB_ONE_NAME=db1

DB_CONNECTION_TWO=mysql2
DB_TWO_NAME=db2

In my config/database.php file I have the following reference:在我的 config/database.php 文件中,我有以下参考:

'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_ONE_NAME', 'db1'),
        'username' => env('DB_USERNAME', 'user'),
        'password' => env('DB_PASSWORD', 'root'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => 'InnoDB',
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

'mysql2' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_TWO_NAME', 'db2'),
        'username' => env('DB_USERNAME', 'user'),
        'password' => env('DB_PASSWORD', 'root'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => 'InnoDB',
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

In my first migration file, I have this:在我的第一个迁移文件中,我有这个:

<?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateUsersTable extends Migration
    {
  
      public function up()
      {
        Schema::connection('mysql')->create('users', function (Blueprint $table) {
          $table->id();
          $table->string('name');
          $table->string('email')->unique();
          $table->string('username')->unique();
          $table->timestamps();

          $table->index('id');

    });
}


    public function down()
    {
      Schema::connection('mysql')->dropIfExists('users');
    }
}

In the second migration table I have this:在第二个迁移表中,我有这个:

<?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class CreateProjectsTable extends Migration
    {
  
      public function up()
      {
        Schema::connection('mysql2')->create('projects', function (Blueprint $table) {
          $table->id();
          $table->foreignId('user_id')->nullable()->constrained('mysql.users')->onDelete('set null');
          $table->string('name')->unique();
          $table->timestamps();

          $table->index(['id', 'user_id']);

    });
}


    public function down()
    {
      Schema::connection('mysql2')->dropIfExists('projects');
    }
}

What could I be doing wrong?我可能做错了什么? I've checked for any duplicate files but couldn't find any errors whatsoever.我检查了任何重复的文件,但找不到任何错误。

Again, I recently upgraded both PHP and MYSQL to their recent versions on my machine.同样,我最近在我的机器上将 PHP 和 MYSQL 升级到了它们的最新版本。 All the extensions needed/required to work on a Laravel project are all installed correctly.在 Laravel 项目上工作所需/需要的所有扩展都已正确安装。

But still, I'm getting this error:但是,我仍然收到此错误:

SQLSTATE[HY000]: General error: 1005 Can't create table `db2`.`projects` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `projects` add constraint `projects_user_id_foreign` foreign key (`user_id`) references `mysql`.`users` (`id`) on delete set null)

Also, when I run this command,此外,当我运行此命令时,

php artisan migrate --pretend

Or或者

php artisan migrate

I still get the same error.我仍然遇到同样的错误。

I have also tried using this:我也试过使用这个:

$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('mysql.users')->onDelete('set null');

but nothing is working.但没有任何效果。 Is there another way to go about this?有没有其他方法可以解决这个问题? If there is, please give me suggestions.如果有,请给我建议。 Thanks for your time.谢谢你的时间。

So after like 14 hours of testing with different kinds of methods, I ended up with what I call "You should have known hack" lol 😂所以在用不同类型的方法进行了大约 14 个小时的测试之后,我最终得到了我所说的“你应该知道 hack”,哈哈😂

I was using the second database connection name inside of the migration table rather than using the database name.我在迁移表中使用了第二个数据库连接名称,而不是使用数据库名称。

My initial code where I used the connection name on the foreign key:我在外键上使用连接名称的初始代码:

  Schema::connection('mysql2')->create('projects', function (Blueprint $table) {
      $table->id();
      $table->foreignId('user_id')->nullable()->constrained('mysql.users')->onDelete('set null');
      $table->string('name')->unique();
      $table->timestamps();

      $table->index(['id', 'user_id']);
  });

What works now!现在什么工作! using the database name and not the connection name on the foreign key:在外键上使用数据库名称而不是连接名称:

 Schema::connection('mysql2')->create('projects', function (Blueprint $table) {
      $table->id();
      **$table->foreignId('user_id')->nullable()->constrained('db1.users')->onDelete('set null');**
      $table->string('name')->unique();
      $table->timestamps();

      $table->index(['id', 'user_id']);
  });

So, the second option works fine.所以,第二个选项工作正常。 I hope this helps someone too!!!我希望这也能帮助别人!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM