如何在 Laravel 4 中使用 UPDATE 或 INSERT?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17317193/
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
How can I use UPDATE OR INSERT with Laravel 4?
提问by Stromgren
I'm building an application in Laravel 4 and I need to run several queries as UPDATE OR INSERT queries to avoid PK violations on duplicate inserts. I haven't been able to find any way to do this with the query builder in Laravel.
我正在 Laravel 4 中构建一个应用程序,我需要运行多个查询作为 UPDATE OR INSERT 查询以避免重复插入时的 PK 违规。我一直无法找到任何方法来使用 Laravel 中的查询构建器来执行此操作。
Can I modify the DB class or something similar? Or will I need to just write pure SQL statements?
我可以修改 DB 类或类似的东西吗?还是我只需要编写纯 SQL 语句?
回答by Zero Zhang
Now we can use User::updateOrCreate()
现在我们可以使用 User::updateOrCreate()
回答by Maktouch
You can use DB::statement. http://laravel.com/docs/database
您可以使用 DB::statement。http://laravel.com/docs/database
DB::statement('INSERT INTO comments (comments) values (?)', array('LOL'));
You can put ON DUPLICATE KEY UPDATE in there.
您可以在其中放置 ON DUPLICATE KEY UPDATE。
There's unfortunately no way to do it (that I know of) with eloquent unless you do something like
不幸的是,除非你做类似的事情,否则没有办法用 eloquent 做到(据我所知)
$user = User::find(1);
if ($user === null) {
$user = new User;
}
$user->name = 'hey';
$user->save();
回答by Zack Huston
It would be very nice if Fluent support ON DUPLICATE KEY UPDATE or INSERT IGNORE but it doesn't seem to. The closest solution I found was to use firstOrCreate() on your model.
如果 Fluent 支持 ON DUPLICATE KEY UPDATE 或 INSERT IGNORE 会非常好,但它似乎没有。我找到的最接近的解决方案是在您的模型上使用 firstOrCreate()。
User::firstOrCreate( array('id'=>1, 'name'=>'hey') );
This may do what you need without writing out the full query in some scenarios.
在某些情况下,这可能会执行您需要的操作,而无需写出完整的查询。