https://qiita.com/qiita-kurara/items/2e3efb4ccbb2489b05c3
laravelで上記のように、1サイトにDBを分けて使用する必要が出てきました。
それで、つまづいた点が
下記のような
外部DBのテーブルを外部キー制約に指定した書き方をした
migrationファイルを実行時にエラーが発生しました。
可否を含めてご存知の方おられたら、ご教授お願い致します。
migrationファイル
$table->unsignedInteger('image_id')->nullable(); $table->foreign('image_id')->references('id')->on('ec_mysql.images')->onDelete('set null');
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, ], 'mysql_oldec' => [ 'driver' => 'mysql', 'read' => [ 'host' => env('DB_HOST_OLDEC', '127.0.0.1'), ], 'write' => [ 'host' => ''// writeは未定義にし、更新クエリでエラーにする ], 'port' => env('DB_PORT_OLDEC', '3306'), 'database' => env('DB_DATABASE_OLDEC', 'forge'), 'username' => env('DB_USERNAME_OLDEC', 'forge'), 'password' => env('DB_PASSWORD_OLDEC', ''), 'unix_socket' => env('DB_SOCKET_OLDEC', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],
どのようなエラーでしょうか?
有難う御座います。
エラー内容は下記になります。
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `tests` add constraint `tests_image_id_foreign` foreign key (`image_id`) references `tests` (`id`) on delete set null)
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
+9 vendor frames
10 database/migrations/2020_03_10_103333_create_tests_table.php:49
Illuminate\Support\Facades\Facade::__callStatic()
+22 vendor frames
33 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
あなたの回答
tips
プレビュー