I am trying to set foreign key of my ‘books’ table with ‘categories’ table using php artisan migrate, but I got the following error:
IlluminateDatabaseQueryException
SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table `books` add constraint `books_category_id_foreign` foreign key (`category_id`) references `categories` (`id`))
books migration file:
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string("image");
$table->string("title");
$table->string("description")->nullable();
$table->string("author");
$table->string("cover");
$table->integer("nod")->nullable();// Number of downloads
$table->integer("rating")->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
categories migration file:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string("title");
$table->string("image");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
I really need help with this to use in my mobile app API. I hope someone can help me.
asked Mar 24, 2020 at 7:05
2
The problem is on the migration itself. Have a look carefully at this
SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table `books` add constraint `books_category_id_foreign` foreign key (`category_id`) references `categories` (`id`))
You are trying to open the categories
table but it basically wasn’t there or wasn’t created yet. If you use GUI like HeidiSQL or Navicat, or PMA, You will be able to see it.
Laravel migration takes the timestamp on the beginning of the file to decide which migration should be migrated first in sequence.
Make sure you create the categories table first before the books table (this also applies for any tables that has reference). Or simply just rename the file (change the timestamp) like E.g:
2020_01_01_1234_create_books_table.php
2020_01_01_5678_create_categories_table.php
to this
2020_01_01_1234_create_categories_table.php
2020_01_01_5678_create_books_table.php
Then run php artisan migrate:fresh
to refresh your migration.
answered Nov 28, 2020 at 1:20
YuraYura
1,8192 gold badges15 silver badges40 bronze badges
I faced the same issue with you since yesterday and I later saw my mistakes, I was able to understand the cause of the problem.
There are so many factors to consider
- Make sure the date for the parent table (categories) is earlier than the date for the child table (books) so that during the migration, the parent table will be created first because the child table might want to reference id in a table that does not exist.
- Make sure to follow the convention for naming
-
you can refactor your migration file like this
$table->foreignId(‘category_id’)->constrained(‘categories’);
or
$table->foreignId(‘category_id’)->constrained();
example of one of my migration files
public function up()
{
Schema::create('project_details', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
$table->id();
$table->foreignId('project_id')->constrained()->onDelete('cascade');
$table->string('name', 150)->nullable();
$table->string('description', 600)->nullable();
$table->string('location', 150)->nullable();
$table->integer('completed_percent')->nullable()->default(0);
$table->foreignId('manager_id')->constrained('staffs');
$table->foreignId('sponsor_id')->constrained('sponsors')->nullable();
$table->foreignId('donor_id')->constrained('sponsors')->nullable();
$table->foreignId('mda_id')->constrained('sponsors')->nullable();
});
}
answered Sep 22, 2020 at 22:08
KINGSLEY OKPARAKINGSLEY OKPARA
5291 gold badge4 silver badges14 bronze badges
2
You try get category for book before you create category table and book table cant understand what you referenced for.
Solution #1
Declare your category table before book table, just rename date in migration file name. Category table must be created before book table.
Solution #2
Create reference after you create category table.
Remove
$table->foreign('category_id')->references('id')->on('categories');
from book migration and create references after you up category table.
categories migration file:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string("title");
$table->string("image");
$table->timestamps();
});
Schema::table('books', function (Blueprint $table) {
$table->foreign('category_id')->references('id')->on('categories');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
Main idea is make all relations when all tables created.
Also, use php artisan migrate:fresh
for fast wipe and recreate tables
answered Sep 4, 2020 at 8:51
I had the same error just right now.
It has something related to creating those migrations.
The problem I had because I refactored the table name manually and didn’t take care of the connection between the tables and instantly tried to migrate them.
The solution I did and worked for me is I deleted the migrations manually and created them again using php make:magirate
.
Lee Goddard
10.1k3 gold badges46 silver badges60 bronze badges
answered Apr 16, 2020 at 22:55
Rose RiyadhRose Riyadh
4505 silver badges16 bronze badges
1
The table (Categories) you are referencing its «id» is either not created or its created after the «books» table. You can manually delete both tables and create them again with «Categories» been first or you can manually change the date of the «Categories» to a date before the «books» and you are good to go.
answered Dec 12, 2021 at 11:00
Make sure you have such a table in your database. If you use a lot of database, then you need to specify the database for constrained
$connection_db = DB::connection(‘connection_name’)->getDatabaseName();
$table->foreign(‘category_id’)->references(‘id’)->on(«$connection_db.categories»);
answered Jun 15, 2022 at 4:43
Make sure both the tables are created using the same engine. In my case, I created two tables with two different engines (MyISAM and InnoDB). Changing both the table engines to InnoDB did the trick.
answered Jul 30, 2022 at 16:48
#mysql #laravel #migration #laravel-8
Вопрос:
Я создал три таблицы миграции таблица user_container предназначена для хранения сведений о пользователе, таблица admin_table предназначена для хранения сведений об администраторе, таблица blog_table предназначена для хранения блогов .администратор может создавать блоги, поэтому я создаю отношение ключа foriegn для администратора к таблице блогов .когда я пытаюсь перенести таблицы, я получаю следующую ошибку
IlluminateDatabaseQueryException
SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'admin_table' (SQL: alter table `blogs_table` add constraint `blogs_table_admin_id_foreign` foreign key (`admin_id`) references `admin_table` (`id`))
пожалуйста, помогите мне решить эту проблему, я не понимаю, где я ошибся..
структура таблицы миграции
2021_08_11_170129_create_Blogs_table.php
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
class CreateBlogsTable extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('blogs_table', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('price');
$table->string('country');
$table->longText('description');
$table->integer('rating');
$table->longText('image');
$table->unsignedInteger('admin_id');
$table->foreign('admin_id')->references('id')->on('admin_table');
$table->timestamps();
//$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('blogs_table');
}
}
2021_08_12_121933_create_admin_table.php
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
class CreateAdminTable extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('admin_table', function (Blueprint $table) {
$table->id();
$table->string('firstName');
$table->string('lastName');
$table->string('email')->unique();
$table->string('mobile');
$table->string('password');
$table->timestamps();
//$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('admin_table');
}
}
Комментарии:
1. Ошибка довольно очевидна… Как вы можете ссылаться на другую таблицу, которая не была создана ? Сначала вы создаете
blogs_table
, а затем создаетеadmin_table
, поэтому при созданииblogs_table
и запуске миграции она не будет существоватьadmin_table
для ссылки…
Ответ №1:
Сначала вы пытаетесь запустить миграцию в таблице блогов, а затем запустите миграцию в таблице администратора.
Миграция Laravel использует метку времени в начале файла, чтобы решить, какая миграция должна быть перенесена первой в последовательности.
Убедитесь, что вы сначала создали таблицу администратора перед таблицей блога (это также относится ко всем таблицам, на которые есть ссылки). Или просто переименуйте файл (измените метку времени), например:
2021_08_12_121933_create_admin_table.php
2021_08_11_170129_create_Blogs_table.php
К этому:
2021_08_11_121933_create_admin_table.php
2021_08_12_170129_create_Blogs_table.php
Затем запустите php artisan migrate:fresh
, чтобы обновить миграцию.
Комментарии:
1. @DevopsTraining вы не должны получать ошибки с этим решением, вам нужно переименовать оба файла
2. Вы также правы, это также нормально, если мы переименуем оба файла.
Ответ №2:
Когда вы настраиваете внешний ключ $table->foreign('admin_id')->references('id')->on('admin_table');
, таблица admin_table еще не существует.
Измените имя миграции таблицы admin_table, которая будет запущена перед именем страницы блога.
2021_08_11_121933_create_admin_table.php
вместо
2021_08_12_121933_create_admin_table.php
I am trying to set foreign key of my ‘books’ table with ‘categories’ table using php artisan migrate, but I got the following error:
IlluminateDatabaseQueryException SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table `books` add constraint `books_category_id_foreign` foreign key (`category_id`) references `categories` (`id`))
books migration file:
public function up() { Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->integer('category_id')->unsigned(); $table->foreign('category_id')->references('id')->on('categories'); $table->string("image"); $table->string("title"); $table->string("description")->nullable(); $table->string("author"); $table->string("cover"); $table->integer("nod")->nullable();// Number of downloads $table->integer("rating")->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('books'); }
categories migration file:
public function up() { Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string("title"); $table->string("image"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('categories'); }
I really need help with this to use in my mobile app API. I hope someone can help me.
Answer
The problem is on the migration itself. Have a look carefully at this
SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table `books` add constraint `books_category_id_foreign` foreign key (`category_id`) references `categories` (`id`))
You are trying to open the categories
table but it basically wasn’t there or wasn’t created yet. If you use GUI like HeidiSQL or Navicat, or PMA, You will be able to see it.
Laravel migration takes the timestamp on the beginning of the file to decide which migration should be migrated first in sequence.
Make sure you create a the categories table first before the books table (this also applies for any tables that has reference). Or simply just rename the file (change the timestamp) like E.g:
2020_01_01_1234_create_books_table.php
2020_01_01_5678_create_categories_table.php
to this
2020_01_01_1234_create_categories_table.php
2020_01_01_5678_create_books_table.php
Then run php artisan migrate:fresh
to refresh your migration.
Attribution
Source : Link , Question Author : Veasna WT , Answer Author : Tamma