dimanche 5 août 2018

How do I make the most effective and efficient logic to check the data in the database exist or not?

I use laravel 5.6

I have a json file containing 500 thousand records. I want to create a logic to check whether the id of each record already exists or not in the database. If it doesn't already exist, then there will be a data insert process. If it already exists, there will be a data update process

I have made logic. I just want to make sure whether my logic is effective or not

My logic code like this :

$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
    $data = \DB::table('details')->where('id', '=', $value['Code'])->get();
    if ($data->isEmpty()) {
        \DB::table('details')->insert(
            [
                'id' => $value['Code'],
                'number' => $value['Number'],
                ...
            ]
        );
    }
    else {
        \DB::table('details')
            ->where('id', '=', $value['Code'])
            ->update([
                'id' => $value['Code'],
                'number' => $value['Number'],
                ...
            ]);
    }
}

The code is working. But the process seems really long

Do you have another solution that is better?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire