Laravel 使用 Query Builder 进行 upsert 操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37740944/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:58:41  来源:igfitidea点击:

Laravel upsert operations with Query Builder

laravellaravel-5eloquentquery-builderlaravel-query-builder

提问by Happy Coder

In one of the my worker scripts to store aggregate counts based on some metrics, I am not using Eloquent as the queries are a little complex and and it is easy to write using query builder. I am currently getting the values from the database and I need to insert/update it in the database. Can an upsert operation is possible by using the save() method can be achieved using Query Builder? Or do I need to check every time whether this entry is in database?

在我的一个基于某些指标存储聚合计数的工作脚本中,我没有使用 Eloquent,因为查询有点复杂,并且使用查询构建器很容易编写。我目前正在从数据库中获取值,我需要在数据库中插入/更新它。可以使用查询生成器实现使用 save() 方法的 upsert 操作吗?还是我每次都需要检查这个条目是否在数据库中?

I have a total of 100,000 entries and would like to run it as a daily job. So if I need to check whether a particular entry is there in DB, I need to access the database that many times. Is there an alternative solution for this ?

我总共有 100,000 个条目,并希望将其作为日常工作运行。因此,如果我需要检查数据库中是否存在特定条目,则需要多次访问数据库。是否有替代解决方案?

I am thinking about creating two model classes, one using Eloquent and one using query builder. Can I use my custom query in the Eloquent model?

我正在考虑创建两个模型类,一个使用 Eloquent,一个使用查询构建器。我可以在 Eloquent 模型中使用我的自定义查询吗?

回答by Alexey Mezenin

Eloquent has updateOrCreate()method which allows you to do exactly want you want. But Query Builder doesn't have similar method.

Eloquent 有updateOrCreate()方法可以让你做你想做的事。但是 Query Builder 没有类似的方法。

You can build raw query with Query Builder and use INSERT ... ON DUPLICATE KEY UPDATEas upsert solution.

您可以使用 Query Builder 构建原始查询并使用INSERT ... ON DUPLICATE KEY UPDATE作为 upsert 解决方案。