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']);
}
推荐文章: