在Laravel中插入数据时更新重复数据 [英] Update Duplicate Data when insert data in laravel
问题描述
您好,我已经搜索并尝试解决此问题,但由于耽误您的时间,未能及时找到解决方案. 我正在使用查询生成器在laravel中插入一组数据,以一次插入多个数据.
Hi I've search and try to solve the issue but failed to grab solution sorry for taking your time. I am inserting a set of data in laravel with the query builder to insert multiple data at a time.
DB::table('table')->insert(
array(
array(
'col1' => 'data1',
'col2' => 'data1'
),
array(
'col1' => 'data2',
'col2' => 'data2'
),
)
);
是否有任何方法可以检查表中的col1,col2
值是否存在,然后进行更新,否则进行插入.如果所有数据成功更新或插入,我想从查询结果中返回true
或false
.我想用laravel查询生成器解决它.
谢谢
Is there any way to check if exist the col1,col2
value in table if exist then update otherwise insert. I wanted to get return true
or false
from the query result if all data successfully update or inserted. I wanted to solve it with laravel query builder.
Thanks
推荐答案
据我所知,Laravel查询构建器不支持此功能. 您可以执行原始MySQL查询:
As far as I know, the Laravel query builder does not support this. You could do a raw MySQL query:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
但这非常混乱且特定于MySQL.
But that is very messy and MySQL specific.
相反,我建议您使用雄辩的ORM:
Instead i would suggest you use the Eloquent ORM:
// Retrieve the flight by the attributes, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
http://laravel.com/docs/5.1/eloquent#插入和更新模型
这篇关于在Laravel中插入数据时更新重复数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!