Laravel Query Builder 的 updateOrInsert 函数的具体细节是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47398368/
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
What are the specifics for Laravel Query Builder's updateOrInsert function?
提问by Matthew Hirt
This function is not in the Laravel documentation, I have found it in the source code however I am not completely sure how it should be used. For example, if I am working with products, I want to either insert or update a product in the database based on its UPC. If a product with the same UPC exists, update it with the new values. If not, insert the new values as a new product. How should this be done using this function?
这个函数不在 Laravel 文档中,我在源代码中找到了它,但是我不完全确定应该如何使用它。例如,如果我正在处理产品,我想根据产品的 UPC 在数据库中插入或更新产品。如果存在具有相同 UPC 的产品,请使用新值更新它。如果不是,则将新值作为新产品插入。应该如何使用此功能完成此操作?
Thank you!
谢谢!
回答by Karl Hill
Insert or update a record matching the attributes, and fill it with values.
插入或更新与属性匹配的记录,并用值填充它。
updateOrInsert(array $attributes, array $values = [])
https://laravel.com/api/master/Illuminate/Database/Query/Builder.html#method_updateOrInsert
https://laravel.com/api/master/Illuminate/Database/Query/Builder.html#method_updateOrInsert
DB::table('products')->updateOrInsert(
[
'upc' => $request->get('upc'),
],
[
'upc' => $request->get('upc'),
'name' => $request->get('name'),
'vendor' => $request->get('vendor'),
'description' => $request->get('description')
]
);