Laravel, create record if it does not exist

4

I have a project in with a database < a href="/ questions / tagged / mysql" class="post-tag" title = 'show questions with the tag "mysql"'> mysql and another with to make a transfer of data from one system to another, the fields from one to another are similar but not the same I do a script like this (I put the code abbreviated):

public function readCars():JsonResponse
{
    $count = 0;
    $data = array();

    $sql = 'SELECT * from Cars';

    $cars = DB::connection('mysql_old')->select($sql);

    foreach ($cars as $car) {
        unset($data);
        $data['id'] = $car->car_id;
        $data['enabled'] = $car->active;

        $exists = Car::where('id',$data['id'])->first();

        if ($exists === null) {
            Car::create($data);
            $count++;
        }
    }
    return $this->jsonOkResponse($count);
}

The code what it does is look for the record in mysql_old , see if it exists with the function ( DB::where... ) and if it does not exist it inserts it.

My question is whether this option is not more optimal with firstOrCreate .

Thanks

    
asked by ilernet 26.06.2018 в 16:05
source

1 answer

1

Yes, it would be more optimal and you could do it in the following way:

public function readCars():JsonResponse
{
    $count = 0;
    $data = [];

    $sql = 'SELECT * from Cars';

    $cars = DB::connection('mysql_old')->select($sql);

    foreach ($cars as $car) {
        $data = [];
        $data['id'] = $car->car_id;
        $data['enabled'] = $car->active;

        $exists = Car::firstOrCreate([
            'id' => $car->car_id
        ], $data);

        $count++;
    }

    return $this->jsonOkResponse($count);
}

The parameters that the firstOrCreate method receives are two arreglos , the first arreglo are the attributes to look for in the table (here for example, we only look for a record in the table for the attribute id ) if it finds it returns that model, if not, it uses the second parameter that is the arrangement of the values for the new model and inserts it directly into the database.

You could also do it with firstOrNew , where what you would do, it would be the same, but instead of saving it directly in the database, you simply want it to work with it and then save it manually, for example:

public function readCars():JsonResponse
{
    $count = 0;
    $data = [];

    $sql = 'SELECT * from Cars';

    $cars = DB::connection('mysql_old')->select($sql);

    foreach ($cars as $car) {
        $data = [];
        $data['id'] = $car->car_id;
        $data['enabled'] = $car->active;

        // Lo instancia si ya existe en la base de datos
        // o lo instancia desde el arreglo $data
        $exists = Car::firstOrNew([
            'id' => $car->car_id
        ], $data);

        $exists->save();

        $count++;
    }

    return $this->jsonOkResponse($count);
}
    
answered by 26.06.2018 в 17:24