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

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);
}

Related

Yii2 Check if foreign key exists in migration

I was creating database migration to add foreign keys. But, before that, I want to ensure that there are foreign key constraints for the given name.
$this->addForeignKey('fk-product-user_id', '{{%product}}', 'user_id', '{{%user}}', 'id');
How can I check if there is already a foreign key named fk-product-user_id exists?
To check the foreign key constraints before adding foreign key. Just fetch the table schemas and check from that.
public $tableName = '{{%product}}';
/**
* {#inheritdoc}
*/
public function safeUp()
{
$tableSchema = Yii::$app->db->schema->getTableSchema($this->tableName);
if (!isset($tableSchema->columns['user_id'])) {
$this->addColumn($this->tableName, 'user_id', $this->integer()->after('id'));
}
if (array_key_exists('fk-product-user_id', $tableSchema->foreignKeys) == false) {
$this->addForeignKey('fk-product-user_id', $this->tableName, 'user_id', User::tableName(), 'id');
}
}

Laravel - Integrity constraint violation: 1452 Cannot add or update a child row

I am importing some content from remote WP database to local DB with laravel. I have set up the tables inventories and contents.
Inventories table looks like this:
Schema::create('inventories', function (Blueprint $table) {
$table->increments('id');
$table->integer('remote_id')->unsigned();
$table->integer('local_id')->unsigned();
$table->string('local_type');
$table->timestamps();
$table->foreign('local_id')->references('id')->on('contents')->onDelete('cascade');
});
This is the contents table:
Schema::create('contents', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('ct_id')->unsigned();
$table->foreign('ct_id')->references('id')->on('content_types');
$table->integer('cms_id');
$table->string('title');
$table->string('slug');
$table->text('excerpt');
$table->mediumText('body');
$table->string('password');
$table->integer('parent_id');
$table->timestamps();
});
I have made functions to import all and import single posts from remote WP DB. This is the import for all posts:
public function all()
{
$include = array_diff($this->indexable, ['folder']);
$publishedPostsIDs = $this->import($include);
$this->deleteOldContent($publishedPostsIDs);
}
private function import($include)
{
$posts = Post::where('post_status', 'publish')->whereIn('post_type', $include)->get();
foreach ($posts as $post) {
$publishedPostsIDs[] = $post->ID;
$this->contentInterface->updateOrCreateInventory($post->ID);
}
return $publishedPostsIDs;
}
public function updateOrCreateInventory($remoteId)
{
$this->contentInterface->updateOrCreateInventory($remoteId);
}
private function deleteOldContent($publishedPostsIDs)
{
$contentToDelete = Content::whereNotIn('cms_id', $publishedPostsIDs)->get();
if (count($contentToDelete) > 0) {
foreach ($contentToDelete as $content) {
$content->delete();
}
}
}
So, when I am importing all, I just go to the route that goes to all function, and all the posts from remote WP DB that are not of post type folder are imported. If I want to import a single post from remote DB, then I have a route that goes directly to the updateOrCreateInventory function. I also have import for the posts of type folder, which is basically almost the same as the function all.
public function folder()
{
$include = ['folder'];
$importResult = $this->import($include);
return $importResult['imported'];
}
The problem I have is that when I am importing all folders at once I get an error:
QueryException in Connection.php line 729: SQLSTATE[23000]: Integrity
constraint violation: 1452 Cannot add or update a child row: a foreign
key constraint fails (middleton.inventories, CONSTRAINT
inventories_local_id_foreign FOREIGN KEY (local_id) REFERENCES
contents (id) ON DELETE CASCADE) (SQL: insert into inventories
(remote_id, updated_at, created_at) values (7512, 2017-11-13
15:33:17, 2017-11-13 15:33:17))
But, if I try to import that same folder individually , or to be more exact that same post of type folder, I don't get any error and the post is imported. How is that possible?
You $this->contentInterface creates an Inventory model without the "local_id" field specified, but it is required by the foreign key.
Find the place where you create the Inventory model and provide a valid "local_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.

Laravel migration can't add foreign key

I'm trying to write a laravel database migration but I'm getting the following error about a foreign key:
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table (SQL: alter table `subcategories` add constraint subcategories_category_id_foreign foreign key (`category_id`) references `categories` (`id`))
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table
The categories and subcategories tables do get created but the foreign key doesn't. Here's my migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function ($table) {
$table->increments('id')->unsigned();
$table->string('name')->unique();
});
Schema::create('subcategories', function ($table) {
$table->increments('id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('name')->unique();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('categories');
Schema::drop('subcategories');
}
}
Any ideas? Thanks!
You should create column before creating a foreign key:
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
Documentation: http://laravel.com/docs/5.1/migrations#foreign-key-constraints
Laravel 7, 8
As Limon Monte mentioned firstly create column then add foreign key constraints
$table->foreignId('category_id');
$table->foreign('category_id')->references('id')->on('categories');
Integer didn't work for me. Rather, I used bigInteger to create foreign key:
$table->bigInteger('category_id')->unsigned()->index()->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
I forgot to add ->get() to the methods I called.

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 ???