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...
推荐答案
根据 Eloquent 模型方法updateOrCreate()"的定义
As per the Definition of the Eloquent Model Method "updateOrCreate()"
function updateOrCreate(array $attributes, array $values = []){}
function updateOrCreate(array $attributes, array $values = []){}
它需要两个参数......
it takes two argument ...
- 一个是在记录存在时要使用的属性检查数据库
- second 是您要创建或更新的新属性值
<小时>
AppInfo::updateOrCreate(['app_id' => $postData['appId']],
['contact_email' => $postData['contactEmail']]);
这篇关于Laravel 5.1 创建或更新重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!