带有自动增量数据库的 Laravel updateOrCreate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27479339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel updateOrCreate with auto-incremental database
提问by saimcan
My purpose is to update if the value exists, else inserts a new rowin the database table after submitting the form.
我的目的是更新值是否存在,否则在提交表单后在数据库表中插入一个新行。
The problem is, the function here adds new columnsin db table instead of updating them.
问题是,这里的函数在 db 表中添加新列而不是更新它们。
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.)
我的数据库表是这样的:
1. myPrimaryKey(不是自动增量,可以在模型上填充。)
2. myAutoIncrementalField(自动增量,不能在模型上填充。)
Thank you in advance.
先感谢您。
回答by Jarek Tkaczyk
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.
作为第一个参数传递唯一的字段数组,或者在您的情况下是主键。非唯一字段在这里显然没有意义,就像在 PK 中传递任何东西一样。
2nd param is an array of values that should be updated/created too, but being ignored in the unique/pk search.
第二个参数是一个也应该更新/创建的值数组,但在 unique/pk 搜索中被忽略。
回答by Jerodev
You cannot use where functions with this method. You have to include the where clauses in the array.
您不能在此方法中使用 where 函数。您必须在数组中包含 where 子句。
MyModel::updateOrCreate(array(
'myField' => 'myValue',
'myAutoIncrementalField' => '5',
'myPrimaryKey' => '8'
));