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

I am using laravel
My Error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`bd_name`.`inpatients`, CONSTRAINT `inpatients_ward_id_foreign` FOREIGN KEY (`ward_id`) REFERENCES `wards` (`id`)) (SQL: insert into `inpatients` (`patient_id`, `ward_id`, `updated_at`, `created_at`) values (2010101, 06, 2020-10-14 06:44:12, 2020-10-14 06:44:12))
My inpatient table is here:
$table->bigIncrements('id');
$table->timestamps();
$table->unsignedBigInteger('patient_id');
$table->foreign('patient_id')->references('id')->on('patients');
$table->char('discharged',4)->default('NO'); // YES | NO
$table->unsignedBigInteger('ward_id');
$table->foreign('ward_id')->references('id')->on('wards');
inpatientController
$INPtable = new inpatient;
$INPtable->patient_id = $request->reg_pid;
$INPtable->ward_id = $request->reg_ipwardno;
Inpatient Model
protected $fillable = [
'ward_id','patient_id',
];
public function ward() {
return $this->belongsTo('App\Ward');
}
public function patient() {
return $this->belongsTo('App\Patients');
}
I don't understand what's going wrong here. Please help me.

The error will be mostly because of the table which you referred as foreign key in inpatient table i.e ward table. You first have to enter data in the ward table, and that data you can refer in the child table. If key 6, is not present in the ward table, insert it first into the table, then do the insertion in the inpatient table.
Hope you got it. Thank You :)

My ward table has ward_no also. I have passed ward_no instead of ward id. That's why the error.

Related

How to delete related records on other table

I tried this
CreatedPlan::where('meal_type_id',config('const.PLAN.__MORNING_MEAL'))->whereYear('calendar_date', $targetYear)->whereMonth('calendar_date',$targetMonth)->get();
However following error happened.
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (plan.created_plans_foods, CONSTRAINT created_plans_foods_created_plan_id_foreign FOREIGN KEY (created_plan_id) REFERENCES created_plans (id)) (SQL: delete from created_plans where __id = 1 and year(calendar_date) = 2022 and month(calendar_date) = 04) in file /Users/Developments/plan/bb/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 669
I tried to delete the records of the related table.
The problem is that you are deleting the record of the parent table first and then the child table. This is why laravel gives you the error.
In order to delete this type of case first delete the child table data and then delete the parent table data.
Suppose you have table name users and the other is users_info. The user id is the parent key in the users_info table. so do the following :
First delete from user_info
UserInfo::where('user_id',$userId)->delete();
Then delete it from the users. Hope this will solve your problem .
User::where('id',$userId)->delete();

How to add unique constraint to an existing foreignId column in laravel?

I have an existing table in database with data and I want to add unique constraints to the customer_id column in it.
I tried doing $table->foreignId('customer_id)->unique()->change(). But it doesn't seem to work. The same works for any non foreign fields like string and int.
Error:
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'customer_id' (SQL: alter table `partner_preferences` add `customer_id` bigint unsigned not
null)
foreignId() essentially creates a new column which in your case already exists.
The foreignId method is an alias of the unsignedBigInteger method:
laravel - difference between foreignId() and unsignedBigInteger()
Try this please:
Unique constraint
public function up()
{
// Change the 'table name' according to your needs.
Schema::table("employees", function (Blueprint $table) {
$table->unique('customer_id');
});
}
WARNING: Make sure the column(s) that you're applying this constraint to is actually unique. (Must have unique data.)
Otherwise, an error (SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'XXXX_customer_id_unique') will be thrown.

Why I can't do a migration with constraint foreign key

for a homework i have to do a todolist in laravel 7 i do my db but when i try to create a foreign key to the table task
and a table categories
the program fail with the formula :"SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table tasks add constraint tasks_category_id_foreign foreign key (categ
ory_id) references categories (id) on delete cascade)"
i've done it a lot of time but i don't understand why i doesn't work if someone could explains
the right way to do it
The migration is trying to create the tasks table before categories, the categories table still doesn't exist at the time it tries to create the FK.
Swap the order of your migrations changing its filename. Each migration file at database/migrations has a date-time before the name. Alter it so the tasks migration has a date greater than the categories one.
will Gus Costa is right and you should do as he says but i want to add that your
foreign key should be unsigned
and here you will find some good answers
"General error: 1005 Can't create table" Using Laravel Schema Build and Foreign Keys
// CREATING TABLE
Schema::create('table_name', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('field_id')->unsigned; //for field that contains foreign key constraint
});
// FOREIGN KEY CONSTRAINT
Schema::table('stock', function ($table) {
$table->foreign('field_id')->references('id')->on('some_table')->onDelete('cascade')->onUpdate('cascade');
});

Laravel observer Update Event in not Triggering

I used this in my update function:
$qty = $request->input('checked_out_qty');
DB::table('consumables')->decrement('remaining_qty',$qty );
i keep getting this error:
"SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (fixed.consumables_histories, CONSTRAINT 251075_5c35eb169cb40 FOREIGN KEY (checked_out_qty_id) REFERENCES consumables (id) ON DELETE CASCADE) (SQL: insert into consumables_histories (consumables_id, checked_out_qty_id, checked_out_by_id, status_id, location_id, assigned_to_id, updated_at, created_at) values (1368, 6, 1, 1, 1, , 2019-02-03 08:08:34, 2019-02-03 08:08:34))
but when u refresh the second time, the decrement still happens. what could i be doing wrong?

Passing an id to other controller

$job->created_by = $input['created_by'];
I want to pass user id in this array which is in other table what should I do?
The field is a foreign key.
When I run this it throws an exception
SQLSTATE[23000]: Integrity constraint violation: 1452
Cannot add or update a child row: a foreign key constraint fails
(`freight`.`jobs`, CONSTRAINT `approved_by` FOREIGN KEY (`created_by`)
REFERENCES `users` (`id`))
(SQL: insert into `jobs`
(`company_id`, `origin`, `commodity`, `destination`,
`created_by`, `approved_by`, `date`, `carrier`, `consolidator`,
`overseas_agt`, `prepaid_fob`, `free_time`, `wt_pcs`,
`updated_at`, `created_at`)
values (2, , , , asdsadasdsad, asdsadasdsad, , , , , , , ,
2015-11-26 07:32:02, 2015-11-26 07:32:02)
)
You have initialize the field as unsigned in the DB Migration.
as:
$table->integer('user_id')->unsigned();
Here user_id is a primary key of another table.
Alter the table and run migration again.
It will work definitely.
I found what I did wrong I have to give the id of the user that is currently active the correct way is as follow
$job->created_by = \Auth::user()->id;

Resources