integrity violation while seeding - mysql

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.

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

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

What does this SQL error mean? [duplicate]

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.

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.

Laravel 5.1 Migration and Seeding Cannot truncate a table referenced in a foreign key constraint

I'm trying to run the migration (see below) and seed the database, but when I run
php artisan migrate --seed
I get this error:
Migration table created successfully.
Migrated: 2015_06_17_100000_create_users_table
Migrated: 2015_06_17_200000_create_password_resets_table
Migrated: 2015_06_17_300000_create_vehicles_table
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
)) (SQL: truncate `users`)
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
))
I looked up what this error is supposed to mean, and also found examples of other people running into the same problem, even just related to using MySQL, and their solutions, but applying:
DB::statement('SET FOREIGN_KEY_CHECKS=0;'); and
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Within down() doesn't seem to work and when I run describe in MySQL the tables look right.
The migrations are named properly to make sure the users table is migrated first, and then vehicles so the foreign key can be applied, and the tables being setup up correctly suggests the migrations were run, but then the error occurs. I dropped and recreated the DB and tried it again and it is the same result. I also don't understand why it is trying to truncate on the first migration and seed of the database, I wouldn't have thought that would occur when you tried to run php artisan migrate:refresh --seed.
// 2015_06_17_100000_create_users_table.php
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username', 60)->unique();
$table->string('email', 200)->unique();
$table->string('password', 255);
$table->string('role')->default('user');
$table->rememberToken();
$table->timestamps();
});
}
}
public function down()
{
Schema::drop('users');
}
// 2015_06_17_300000_create_vehicles_table.php
class CreateVehiclesTable extends Migration
{
public function up()
{
Schema::create('vehicles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('make');
$table->string('model');
$table->string('year');
$table->string('color');
$table->string('plate');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
}
public function down()
{
Schema::drop('vehicles');
}
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
App\User::truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
And it works!
As the error says, you can not truncate tables referenced by foreign keys. Delete should work though...
DB::table('some_table')->delete();
before drop
Schema::disableForeignKeyConstraints();
and before close run method
Schema::enableForeignKeyConstraints();
To clear a table using Eloquent:
Model::query()->delete();
Example using default user model
User::query()->delete();
I faced the same issue with my Role and Permission setup and this is what I did that worked as I wanted. Truncate() will reset the Increment column to 1 but throw a foreign key error while delete on the other hand works fine but doesn't reset the increment column, so I did the following in my Seeder's file (i.e RoleSeeder.php in my case)
1. [ delete() method ]
$roles = [];
... // Some foreach statement to prepare an array of data for DB insert()
// Delete and Reset Table
DB::table('roles')->delete();
DB::statement("ALTER TABLE `roles` AUTO_INCREMENT = 1");
// Insert into table
DB::table('roles')->insert($roles);
This will cascade all other child tables attached to the roles table. in my case users_roles table. This way I avoided disabling and enabling foreign key checks.
2. Something to put in mind / Second Approach [ truncate() method ]
if you don't have the intention of deleting all the data stored in the child's table (in my case users_roles table) ... You can go with truncate() and then in the DatabaseSeeders.php file you disable and enable foreign key check. As I tested this and the users_roles data was intact, the seed on affected roles table.
//RoleSeeders.php File
$roles = [];
... // Some foreach statement to prepare an array of data for DB insert()
// Truncate Table
DB::table('roles')->truncate();
// Insert into table
DB::table('roles')->insert($roles);
Then in the DatabaseSeeder.php file, you do;
public function run()
{
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$this->call([
RoleSeeder::class,
]);
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
But I prefer the delete() method, since I don't have to disable/enable the foreign key check
you can use
DB::table('your_table_name')->delete();
to empty a table, this won't delete the table structure. But the auto increment id will not start from initial number.
Here is what works for me every time.
When you're adding the foreign key, make sure to add cascade.
the syntax is like this
$table->foreign('column')->references('id')->on('table_name')->onDelete('cascade');
Make sure to replace id with whatever field is applicable for you.
Now before running the seeding add this instead of trucate
DB::statement('DELETE FROM table_name');
It will delete all the data.
Hope this helps.
You could just drop it with.
$table->dropForeign('posts_user_id_foreign');
I'm using Laravel 7.x, this worked for me. Goes without saying that it should only be used in development. To read more, check it out here.
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
// the Eloquent part and disabling and enabling of foreign keys is only intended for development
Eloquent::unguard();
//disable foreign key check for this connection before running seeders
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$this->call(RolesTableSeeder::class);
$this->call(UsersTableSeeder::class);
// supposed to only apply to a single connection and reset it's self
// but I like to explicitly undo what I've done for clarity
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
}