Laravel updateOrCreate with automatic incremental database

My goal is to update if this value exists, otherwise it inserts a new row into the database table after the form is submitted.

The problem is that here the function adds new columns to the db table instead of updating.

Here is my function:

MyModel::updateOrCreate(array( 'myField' => 'myValue', )) ->where('myAutoIncrementalField', '=', '5') ->where('myPrimaryKey', '=', '8'); 

My database table is this:
1. myPrimaryKey (not automatically incremental and populated on the model.)
2. myAutoIncrementalField (automatic increment and cannot be filled on the model.)

Thanks in advance.

+6
source share
2 answers

Here is how you use this method:

 Model::updateOrCreate( ['primary_key' => 8], ['field' => 'value', 'another_field' => 'another value'] ); 

As the first parameter, pass an array of fields that are unique or in your case the primary key. Unusual fields here do not make sense, obviously, as if transmitting something along with the PC.

2nd param is an array of values ​​that should be updated / created, but ignored in a unique / pk search.

+22
source

You cannot use functions with this method. You must include where clauses in the array.

 MyModel::updateOrCreate(array( 'myField' => 'myValue', 'myAutoIncrementalField' => '5', 'myPrimaryKey' => '8' )); 
+1
source

Source: https://habr.com/ru/post/979600/


All Articles