简介
添加和更新是比较常用的操作,下面总结一下
1.添加
// 先填充模型
$user = new User(['name' => 'test123','email' => 'test@test.com'.random_int(10,99),'email_verified_at' => '2021-1-5','password' => bcrypt('123456'),'remember_token' => 'ABABAB','status' => 0,]);// 或者
$user = new User();
$user->fill(['name' => 'test123','email' => 'test@test.com'.random_int(10,99),'email_verified_at' => '2021-1-5','password' => bcrypt('123456'),'remember_token' => 'ABABAB','status' => 0,]);
// 调用 save() 保存数据
$bool = $user->save(); // 返回成功或者失败
// 此时$user模型已经被填充了数据并且已保存到数据库
$user = User::create(['name' => 'test123','email' => 'test@test.com'.random_int(10,99),'email_verified_at' => '2021-1-5','password' => bcrypt('123456'),'remember_token' => 'ABABAB','status' => 0,]);
2.修改
$bool = User::find(15)->update(['name' => 'test1234',]);
//或
$user = User::find(15);
$user->name = 'test1234';
$user->save();
3.查找返回或添加
// 不存在则添加
$user = User::firstOrCreate(['id'=>15],['name' => 'test123','email' => 'test@test.com'.random_int(10,99),'email_verified_at' => '2021-1-5','password' => bcrypt('123456'),'remember_token' => 'ABABAB','status' => 0,]);dd($user);
4.查找修改或添加
// 存在记录则修改,否则添加
$user = User::updateOrCreate(['id'=>15],['name' => 'test123','email' => 'test@test.com'.random_int(10,99),'email_verified_at' => '2021-1-5','password' => bcrypt('123456'),'remember_token' => 'ABABAB','status' => 0,]);