Laravel 5.1创建或更新副本 [英] Laravel 5.1 Create or Update on Duplicate
问题描述
在Laravel 5.1中,对于MySQL插入,我想查看记录是否已存在,并重复进行更新,或者如果不存在则创建新记录.
In Laravel 5.1, for MySQL insert, I want to see if the record already exists and update on duplicate or create new if none exists.
我已经搜索过答案,其中的答案是旧的laravel版本.在一个旧主题中,它说去年在核心中添加了新的updateOrCreate()
方法.但是当我尝试这样做时,出现了错误:
I have already searched SO where the answers were for old laravel versions. In one of the old topics it said that a new updateOrCreate()
method was added in core last year. But when I try that, I am getting the error:
Integrity constraint violation: 1062 Duplicate entry '1' for key 'app_id'
这是我使用的查询:
AppInfo::updateOrCreate(array(
'app_id' => $postData['appId'],
'contact_email' => $postData['contactEmail']
));
app_id
是该表中的唯一外键,我想更新记录(如果存在)或创建一个新记录.我尝试搜索5.1文档,但找不到所需的信息.有人可以在这里指导我吗...
Where app_id
is the unique foreign key in that table and I want to update the record if exists or create a new one. I have tried searching the 5.1 docs and couldn't find the info I need. Can someone guide me here please...
推荐答案
按照雄辩的模型方法"updateOrCreate()"的定义
As per the Definition of the Eloquent Model Method "updateOrCreate()"
function updateOrCreate(array $ attributes,array $ values = []){}
function updateOrCreate(array $attributes, array $values = []){}
需要两个参数...
- 一个属性是您要用来在数据库中检查记录是否存在的属性
- second是您要创建或更新的新属性值
AppInfo::updateOrCreate(['app_id' => $postData['appId']],
['contact_email' => $postData['contactEmail']]);
这篇关于Laravel 5.1创建或更新副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!