Laravel updateorcreate

有时候我们需要判断某条数据是否存在,如果存在更新,否则插入,那可能你需要`updateorcreate`
如下测试我输出了每次执行的sql
>>> \App\Models\Admin\User::updateorcreate(['name'=>'php'],['email'=>'php@qq
.com'])
mysql[SQL] select * from `users` where (`name` = ?) limit 1 in 1 s
      bindinds: ["php"]
mysql[SQL] update `users` set `email` = ?, `updated_at` = ? where `id` = ? in 89
 s
      bindinds: ["php@qq.com","2015-12-09 03:29:16",1]
=> <App\Models\Admin\User #000000000ae3f51800000000730c4bfa> {
       id: 1,
       name: "php",
       email: "php@qq.com",
       created_at: "2015-03-28 08:36:27",
       updated_at: "2015-12-09 03:29:16"
   }

>>> \App\Models\Admin\User::where('name','python')->get()
mysql[SQL] select * from `users` where `name` = ? in 2 s
      bindinds: ["python"]
=> <Illuminate\Database\Eloquent\Collection #000000000ae3f52400000000730c4bfa> [
]
>>> \App\Models\Admin\User::updateorcreate(['name'=>'python'],['email'=>'python@qq.c
om'])
mysql[SQL] select * from `users` where (`name` = ?) limit 1 in 1 s
      bindinds: ["python"]
mysql[SQL] insert into `users` (`name`, `email`, `updated_at`, `created_at`) val
ues (?, ?, ?, ?) in 64 s
      bindinds: ["python","python@qq.com","2015-12-09 03:30:42","2015-12-09 03:30:42
"]
=> <App\Models\Admin\User #000000000ae3f51a00000000730c4bfa> {
       name: "python",
       email: "python@qq.com",
       updated_at: "2015-12-09 03:30:42",
       created_at: "2015-12-09 03:30:42",
       id: 36
   }

updateorcreate如同:

$list = \App\Models\Admin\User::where(array('name' => 'php'))->get()->toArray();
if(empty($list)){
  \App\Models\Admin\User::create(array('name' => 'php','email' => 'php@qq.com'));
} esle{
 $list->update(['email' => 'php@qq.com']);
}
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 6
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!