簡體   English   中英

異常:SQLSTATE[23000]:違反完整性約束:1452 無法添加或更新子行:外鍵約束失敗

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM