BossRana
BossRana

Reputation: 1

Why my updateOrInsert doesn't work in laravel 9x

I use updateOrInsert to avoid duplicate data, why doesn't the Update function work and always insert data?

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\Wip;
use App\Models\db2;

class WipController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $tgl_skrg = date('Y-m-d 00:00:00');
        $tgl_skrg2 = date('Y-m-d 23:00:00');
        $nilai = '00017';
       
        $db2s = DB::connection('mysql2')->table("wip_tracking_1")->get();
        
        $data = json_decode($db2s, true);

        foreach ($data as $db2 ){
           DB::table('wip_tracking')
            ->updateOrInsert(
                [
                "TP" =>$db2 ['TP'],
                "TP_code"=>$db2 ['TP_code'],
                "VIN"=>$db2 ['VIN'] ,
                "Flag"=>$db2 ['Flag'] ,
                "Suffix"=>$db2 ['Suffix'] ,
                "Color_Code"=>$db2 ['Color_Code'] ,
                "Scan_date"=>$db2 ['Scan_date'] ,
                "Production_date"=>$db2 ['Production_date'] ,
                "Production_shift"=>$db2 ['Production_shift'] ,
                "Model_code"=>$db2 ['Model_code'] ,
                "Brand"=>$db2 ['Brand'] ,
                "Destination_code"=>$db2 ['Destination_code'] ,
                "WIP_code"=>$db2 ['WIP_code'] ,
                "ADM_Production_ID"=>$db2 ['ADM_Production_ID'] ,
                "Plan_delivery_date"=>$db2 ['Plan_delivery_date'] ,
                "created_at" => date('Y-m-d H:i:s'),
                ],
                [
                    "ADM_Production_ID"=> $db2['ADM_Production_ID']
                ],
                [
                    "VIN"=> $db2['VIN']
                ],

            );
            
          
        } 
                    
 
    }

Upvotes: 0

Views: 89

Answers (1)

Matt
Matt

Reputation: 11

updateOrInsert should receive two parameter arrays. The first one is a conditional array, which will check for the records and second array of columns and values to be updated or inserted.

e.g.

DB::table('users')
    ->updateOrInsert(
        ['email' => '[email protected]', 'name' => 'John'],
        ['votes' => '2']
    );

first array ['email' => '[email protected]', 'name' => 'John'] will look for matching column => value pairs.

second array ['votes' => '2'] will update or insert data based on findings.

https://laravel.com/docs/9.x/queries#update-or-insert

In your case, it seems that you're trying to match a lot of values in your first array, which might be the reason why exact match is never found and it's always producing a new entry, try to limit and keep your conditional array more spcific.

Upvotes: 1

Related Questions