![](/img/trans.png)
[英]SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
[英]Exception: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
供應商表
Schema::create('suppliers', function (Blueprint $table) {
$table->id();
$table->string('supplier_name');
});
測試供應商表
Schema::create('test_suppliers', function (Blueprint $table) {
$table->id();
$table->integer('supplier_id')->nullable();
$table->foreign('supplier_id')->references('suppliers')->on('id');
$table->dateTime('started_at')->nullable();
$table->dateTime('finished_at')->nullable();
$table->timestamps();
});
在這里,當我嘗試插入 TestSuppliers Model 時,我遇到了這個問題
foreach ($itest_suppliers_data as $itest_supplier) {
$supplier_name = $arrayhave['supplier_name'];
$supplier_id = Supplier::where('supplier_name', $supplier_name)->pluck('supplier_id');
TestSuppliers::insert([ // noticed that test_suppliers_table is empty
'started_at' => date("Y-m-d H:i:s", time()),
'supplier_id' => $supplier_id,
'finished_at' => date("Y-m-d H:i:s", time()),
]);
您的供應商表架構不正確。 它應該是:
Schema::create('suppliers', function (Blueprint $table) {
$table->id();
$table->string('name');
});
您的下一個問題是您的 $supplier_id 變量是一個 ID 集合,而不是單個 ID。 您應該將其更改為:
$supplier_id = Supplier::where('name', $supplier_name)->first()->id;
pluck
會返回一個集合。 您需要使用value
來獲取實際值:
foreach ($itest_suppliers_data as $itest_supplier) {
$supplier_name = $arrayhave['supplier_name'];
$supplier_id = Supplier::where('supplier_name', $supplier_name)->value('supplier_id');
TestSuppliers::insert([ // noticed that test_suppliers_table is empty
'started_at' => date("Y-m-d H:i:s", time()),
'supplier_id' => $supplier_id,
'finished_at' => date("Y-m-d H:i:s", time()),
]);
這里的value
相當於說Supplier::where('supplier_name', $supplier_name)->first()->supplier_id
並且這當然是假設您知道總會有一個結果。 我認為無論如何對$supplier_id
進行 null 檢查可能是明智的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.