What does this SQL error mean? [duplicate] - mysql

This question already has answers here:
Integrity constraint violation: 1452 Cannot add or update a child row:
(17 answers)
Closed 7 years ago.
I am getting the following error when running a migration on Laravel. It seems the error comes up when it reaches the part of the migration that updates the User table.
SQLSTATE[23000]: Integrity constraint violation: 1452
Cannot add or update a child row: a foreign key constraint fails
(`priatek`.`#sql-52e_a`, CONSTRAINT user_usertypeid_foreign` FOREIGN KEY
(userTypeId`) REFERENCES `UserType` (`userTypeId`))
(SQL: alter table `User` add constraint user_usertypeid_foreign foreign key
(`userTypeId`) references UserType` (`userTypeId`))
Migration
public function up()
{
Schema::create('UserType', function (Blueprint $table) {
$table->increments('userTypeId');
$table->string('name');
$table->string('description')->nullable();
$table->boolean('viewUser');
$table->boolean('viewSponsor');
$table->boolean('viewQuestion');
$table->boolean('createUser');
$table->boolean('createSponsor');
$table->boolean('createQuestion');
});
UserType::create([
'name' => 'Executive',
'viewUser' => 0,
'viewSponsor' => 1,
'viewQuestion' => 0,
'createUser' => 0,
'createSponsor' => 0,
'createQuestion' => 0,
]);
//more UserType creations...
Schema::table('User', function ($table) {
$table->integer('userTypeId')->unsigned();
$table->integer('operatorId')->unsigned();
$table->integer('sponsorId')->unsigned()->nullable();
$table->foreign('userTypeId')->references('userTypeId')->on('UserType');
});
// more unrelated stuff...
}

The problem is when you add the foreign key to the table, all your users must already have a valid userTypeId. But because you are just now creating that new column, they will not have this.
Before you can create the foreign key, you have to make sure all your users have a valid user type (the user type needs to be created and the userTypeId is set appropriately on each user).
So what you need to do is add the additional columns onto the User table, then run some update queries to make sure all users have their userTypeId set, then add the foreign key after the updates are finished.

Related

Unable to rename a foreign column in laravel 5.8 - column not found error

I am trying to rename a foreign column. So I write the following code:
Schema::table('floor_plans', function (Blueprint $table) {
$table->dropForeign(['unit_type_id']);
$table->renameColumn('unit_type_id', 'utd_id');
$table->foreign('utd_id')
->references('id')
->on('unit_type_details')
->onDelete('cascade');
});
But it throws
Doctrine\DBAL\Schema\SchemaException : There is no column with name 'unit_type_id ' on table 'floor_plans'.
at D:\wamp64\www\amenity\vendor\doctrine\dbal\lib\Doctrine\DBAL\Schema\SchemaException.php:85
81| * #return \Doctrine\DBAL\Schema\SchemaException
82| */
83| public static function columnDoesNotExist($columnName, $table)
84| {
> 85| return new self(
86| sprintf("There is no column with name '%s' on table '%s'.", $columnName, $table),
87| self::COLUMN_DOESNT_EXIST
88| );
89| }
Then I tried by turning foreign checks off:
DB::statement('SET FOREIGN_KEY_CHECKS=0');
$table->dropForeign(['unit_type_id']);
$table->renameColumn('unit_type_id ', 'utd_id');
DB::statement('SET FOREIGN_KEY_CHECKS=1');
But same error, the column not found.
Then I tried to drop foreign with exact ForeignKeyConstraint as :
DB::statement('SET FOREIGN_KEY_CHECKS=0');
$table->dropForeign('floor_plans_unit_type_id_foreign');
$table->renameColumn('unit_type_id', 'utd_id');
DB::statement('SET FOREIGN_KEY_CHECKS=1');
$table->foreign('utd_id')
->references('id')
->on('unit_type_details')
->onDelete('cascade');
Still the same error.
I then even tried with Raw SQL as:
DB::statement("ALTER TABLE floor_plans
DROP FOREIGN KEY `floor_plans_unit_type_id_foreign`,
ADD CONSTRAINT `floor_plans_unit_type_detail_id_foreign` FOREIGN KEY (`unit_type_detail_id`) REFERENCES `unit_type_details` (`id`)");
And this gives me the following error:
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'floor_plans_unit_type_id_foreign'; check that column/key exists (SQL: ALTER TABLE floor_plans
DROP FOREIGN KEY `floor_plans_unit_type_id_foreign`,
ADD CONSTRAINT `floor_plans_unit_type_detail_id_foreign` FOREIGN KEY (`unit_type_detail_id`) REFERENCES `unit_type_details` (`id`))
And here is the screenshot of the table.
All I want is to rename unit_type_id to unit_type_detail_id.
#PS: the table is not empty. And, I am happy to run even if you provide me the raw MySQL query.
Their is an additional space on unit_type_id.
Schema::table('floor_plans', function (Blueprint $table) {
$table->dropForeign(['unit_type_id']);//note foreign key already dropped so also you have to make this line also as comment when you test.
//$table->renameColumn('unit_type_id ', 'utd_id');//remove this space and try again
$table->renameColumn('unit_type_id', 'utd_id');//after remove space
$table->foreign('utd_id')
->references('id')
->on('unit_type_details')
->onDelete('cascade');
});

I need to update existing foreign key, but I can't drop it in order to update it

I've got a migration to correct existing foreign key, it looks like this
public function up()
{
Schema::table('content_term', function (Blueprint $table) {
$table->dropForeign('content_term_content_id_foreign');
$table->foreign('content_id')->references('id')->on('content')->onUpdate('cascade')->onDelete('cascade');
});
}
The original table and foregin key looked like this
public function up()
{
Schema::create('content_term', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('content_id')->unsigned();
$table->unsignedInteger('term_id');
$table->foreign('content_id')->references('id')->on('content')->onUpdate('cascade');
$table->foreign('term_id')->references('id')->on('terms')->onDelete('cascade')->onUpdate('cascade');
});
}
I forgot to add onDelete('cascade') for content_id foreign key creation and need to correct that in a new migration.
When I run php artisan migrate with thew latest migration I've added I get this
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'content_term_content_id_foreign'; check that column/key exists (SQL: alter table content_term drop foreign key content_term_content_id_foreign)
MYSQL complains that the foreign key does not exist in content_term table. When I check that table using phpmyadmin I can clearly see that key exists. See attached pic for proof of that.
What's the problem with my new migration, why is this line causing a problem:
$table->dropForeign('content_term_content_id_foreign');

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

i have reply_qs table and postqs table.Postqs_id is foreign key in reply_qs table.when i tried to save the reply_qs form data in database,its showed this error.
ERROR:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a
child row: a foreign key constraint fails (fyp2.reply_qs, CONSTRAINT
reply_qs_postqs_id_foreign FOREIGN KEY (postqs_id) REFERENCES postqs
(id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into reply_qs
(reply, updated_at, created_at) values (saann, 2017-09-22 15:35:03,
2017-09-22 15:35:03))
how i can solve it? and please explain why im getting this error.
reply_qs model :
protected $table = 'reply_qs';
protected $fillable = ['reply'];
public function postqs(){
return $this->hasMany('App\Postqs');
}
postqs model :
public function reply_qs(){
return $this->hasMany('App\Reply_qs');
}
store function:
public function store(Request $request){
$data = $request->all();
$postqs=($request->id);
$reply=Reply_qs::create($data);
$reply->postqs($id);
}
migration:
Schema::create('reply_qs', function (Blueprint $table) {
$table->increments('id')->unique();
$table->text('reply');
$table->timestamps('date');
});
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::table('reply_qs',function(Blueprint $table)
{
$table->integer('postqs_id')->unsigned();
$table->foreign('postqs_id')->references('id')->on('postqs') -
>onDelete('cascade')->onUpdate('cascade');
});
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Your relationships are not correct.
Your Reply_qs model should have this relationship with Postqs
public function postqs()
{
return $this->belongsTo(Postqs::class);
}
Your store function does not look correct and should look something like this
public function store( Request $request )
{
$reply = new Reply_qs();
$reply->text = $request->get('text');
$reply->postqs_id = $request->get('postqs_id');
$reply->save();
}
In your store method, it looks like you are trying to associate the parent Postqs object with the Reply_qs.
You would do this like so
$reply->associate($post);
You need to pass the object and not the id
If you are still struggling with this double check your foreign keys are matching correctly, you may need to implement the association like so
public function postqs()
{
return $this->belongsTo(Postqs::class, 'postqs_id', 'id);
}

integrity violation while seeding

This is my seeder class below
<?php
use Illuminate\Database\Seeder;
class RequestTableSeeder extends Seeder
{
public function run()
{
$faker = Faker\Factory::create();
for($i=1;$i<=5;$i++){
DB::table('requests')->insert([
"location_id"=>$faker->numberBetween(1,5),
"level_id"=>$faker->numberBetween(0,1),
"subject_id"=>$faker->numberBetween(0,1),
"first_name"=>$faker->firstName,
"last_name"=>$faker->lastName,
"contact"=>$faker->unique()->phoneNumber,
"email"=>$faker->unique()->email,
"description"=>$faker->text(1000),
]);
}
}
}
Here is my levelseeder class:
<?php
use Illuminate\Database\Seeder;
class SubjectTableSeeder extends Seeder
{
public function run()
{
$faker = Faker\Factory::create();
for($i=1;$i<=5;$i++)
{
DB::table('subjects')->insert([
"name"=>$faker->text(5),
]);
}
}
}
while i try to seed from the command i get:
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`tutor`.`requests`, CONSTRAINT `requests_level_id_foreign` FOREIGN KEY (`level_id`) REFERENCES `levels` (`id`) ON DELETE CASCADE)
i also checked my subject seeder class.But i could not find the error.This are my seeder class
You are trying to insert a level_id that references a row in the level table that doesn't exist!
In order for this to work your level table needs to be seeded with at least 5 records with the id of 1,2,3,4,5
If you are doing this, maybe the order of your seeders is wrong. Make sure the LevelTableSeeder runs before the RequestTableSeeder.
Further, it seems that subject_id will most likely fail next. This is intended behavior when using foreign keys which are used to ensure database integrity.

SQLSTATE[23000]: Integrity constraint violation during migration in Laravel 4

I have a problem while migrating
Migration File
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterTableMm extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('downloads', function($table){
$table->engine = 'InnoDB';
$table->increments('id')->unsigned();
$table->string('title',255);
$table->string('count',45)->default(0);
$table->timestamps();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
Schema::table('marketing_materials', function($table)
{
$table->string('download_total', 45 )->default(0);
$table->integer('download_id')->unsigned();
$table->foreign('download_id')->references('id')->on('downloads');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function($table)
{
$table->dropForeign('users_user_id_foreign');
});
Schema::drop('downloads');
Schema::table('marketing_materials', function($table)
{
$table->dropForeign('marketing_materials_download_id_foreign');
});
Schema::table('marketing_materials', function($table)
{
$table->dropColumn('download_total');
$table->dropColumn('download_id');
});
}
}
Error Message
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`distributor-local`.`#sql-668_3d`, CONSTRAINT `marketing_mater
ials_download_id_foreign` FOREIGN KEY (`download_id`) REFERENCES `downloads` (`id`)) (SQL: alter table `marketing_materials` add constraint marketing_materials_download_id_foreign fo
reign key (`download_id`) references `downloads` (`id`))
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`distributor-local`.`#sql-668_3d`, CONSTRAINT `marketing_mater
ials_download_id_foreign` FOREIGN KEY (`download_id`) REFERENCES `downloads` (`id`))
I have all the required tables
users
marketing_materials
I just recently migrate my downloads table
Can someone tell me what did I do wrong ?
The part that confuse me the most of that error message is that, all the contents are added the database fine. See the picture below
I also alter my marketing_materials table, and that's also work.
Should I just ignore the error message ???