Laravel updateOrCreate with auto-incremental datab

2019-04-07 20:05发布

My purpose is to update if the value exists, else inserts a new row in the database table after submitting the form.

The problem is, the function here adds new columns in db table instead of updating them.

Here's my function :

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

My database table is like that :
1. myPrimaryKey (not auto incremental and is fillable on model.)
2. myAutoIncrementalField (auto incremental and cannot be fillable on model.)

Thank you in advance.

2条回答
做个烂人
2楼-- · 2019-04-07 20:55

This is how you use this method:

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

As 1st param pass an array of fields that are unique, or in your case, the primary key. Non-unique fields don't make sense here obviously just like passing anything along with the PK.

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

查看更多
爷的心禁止访问
3楼-- · 2019-04-07 21:11

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

MyModel::updateOrCreate(array(
    'myField' => 'myValue',
    'myAutoIncrementalField' => '5',
    'myPrimaryKey' => '8'
));
查看更多
登录 后发表回答