Home > Back-end >  Exception: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a
Exception: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a

Time:04-20

supplier_table

Schema::create('suppliers', function (Blueprint $table) {
$table->id();
$table->string('supplier_name');
});

test_suppliers_table

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

Here when I try to insert into TestSuppliers Model I got this problem

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()),
                ]);

CodePudding user response:

Your schema for the suppliers table is incorrect. It should be:

Schema::create('suppliers', function (Blueprint $table) {
    $table->id();
    $table->string('name');
});

Your next issue is that your $supplier_id variable is a Collection of ids, not a single ID. You should change that to:

$supplier_id = Supplier::where('name', $supplier_name)->first()->id;

CodePudding user response:

pluck would return a collection. You need to use value to get the actual 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()),
    ]);

Here value is equivalent to saying Supplier::where('supplier_name', $supplier_name)->first()->supplier_id and this is of course assuming you know that there will always be a result. I think it's probably wise to do a null check on the $supplier_id regardless.

  • Related