首页 > 解决方案 > SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(未修复)

问题描述

我正在使用 laravel

我的错误:

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

我的住院病床在这里:

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

住院控制器

$INPtable = new inpatient;
$INPtable->patient_id = $request->reg_pid;
$INPtable->ward_id = $request->reg_ipwardno;

住院模型

protected $fillable = [
'ward_id','patient_id',
];

public function ward() {
    return $this->belongsTo('App\Ward');
}

public function patient() {
    return $this->belongsTo('App\Patients');
}

我不明白这里出了什么问题。请帮我。

标签: laraveleloquent

解决方案


该错误主要是因为您在住院表中称为外键的表,即病房表。您首先必须在病房表中输入数据,并且您可以在子表中引用该数据。如果 ward 表中不存在键 6,则先将其插入表中,然后再插入 inpatient 表中。希望你明白了。谢谢你 :)


推荐阅读