Issue
I created Three migration tables user_container table is for storing user details, admin_table is for storing admin details, blog_table is for storing blogs .admin can create blogs so that's why i make a foriegn key relationship for admin to blogs table .when i try to migrate the tables i am getting the following error
Illuminate\Database\QueryException
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`))
please help me to fix this issue i am not getting where did i mistake..
2021_08_11_170129_create_Blogs_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
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 Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
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');
}
}
Solution
When you're setting up the foreign key $table->foreign('admin_id')->references('id')->on('admin_table');
the table admin_table doesnt exist yet.
Change the migration name of the admin_table to be run before that of the blog one.
2021_08_11_121933_create_admin_table.php
instead of
2021_08_12_121933_create_admin_table.php
Answered By - N69S Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.