Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent updateOrInsert

Tags:

eloquent

I would like the eloquent to be able to auto-feed the created_at and updated_at fields, using the following commands below

                DB::table('partida')->updateOrInsert(
                    [
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id
                    ],
                    [
                        'partida_id' => $key,
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id,
                        'partida_data' => (string)$value->partida_data,
                        'placar_mandante' => $value->placar_oficial_mandante,
                        'placar_visitante' => $value->placar_oficial_visitante,
                        'local' => (string)$value->local
                    ]
                );
like image 391
Elvis Reis Avatar asked Jun 05 '26 15:06

Elvis Reis


1 Answers

If you want to use the Eloquent methods properly, use Eloquent and not the query builder.

You can practically do the same with the updateOrCreate() method, which will set the timestamps if the model defines them.

You'll get something like (assuming the Partida model exists):

Partida::updateOrCreate([
        'rodada' => $values->rodada,
        'mandante_fk' => $value->clube_casa_id,
        'visitante_fk' => $value->clube_visitante_id
    ],
    [
        'partida_id' => $key,
        'rodada' => $values->rodada,
        'mandante_fk' => $value->clube_casa_id,
        'visitante_fk' => $value->clube_visitante_id,
        'partida_data' => (string)$value->partida_data,
        'placar_mandante' => $value->placar_oficial_mandante,
        'placar_visitante' => $value->placar_oficial_visitante,
        'local' => (string)$value->local
    ]);
like image 173
Robert Avatar answered Jun 10 '26 07:06

Robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!