【问题标题】:What are the specifics for Laravel Query Builder's updateOrInsert function?Laravel Query Builder 的 updateOrInsert 函数的细节是什么?
【发布时间】:2018-05-04 01:08:05
【问题描述】:

这个函数不在 Laravel 文档中,我在源代码中找到了它,但是我不完全确定应该如何使用它。例如,如果我正在处理产品,我想根据其 UPC 在数据库中插入或更新产品。如果存在具有相同 UPC 的产品,请使用新值对其进行更新。如果没有,请将新值作为新产品插入。应该如何使用这个函数呢?

谢谢!

【问题讨论】:

  • updateOrCreate 返回模型,而 updateOrInsert 返回一个布尔值,但它们的作用相同。但这几乎就是您要寻找的。查看 updateOrCreate 的文档

标签: php mysql laravel laravel-5


【解决方案1】:

插入或更新与属性匹配的记录,并用值填充它。

updateOrInsert(array $attributes, array $values = []) 

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')
    ]
);

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 2017-11-08
    • 2015-12-03
    • 2017-07-30
    • 1970-01-01
    • 2016-08-30
    • 2020-04-26
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多