簡介
新增和更新是比較常用的操作,下面總結一下
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,
]);
5.批次插入
6.批次更新
本作品採用《CC 協議》,轉載必須註明作者和本文連結