一.增删改操作
- 新增方法如下,注意:默认模型接管 created_at 和 updated_at;
$users = new User();
$users->username = '辉夜';
$users->password = '123';
$users->email = 'huiye@163.com';
$users->details = '123';
$users->save();
- 更新,只要是查找到一条数据的情况下使用 save()就是更新;
$users = User::find(321);
$users->username = '夜辉';
$users->save();
- 使用 update()方法实现批量更新;
User::where('username', '夜辉') ->update([ 'username' => '辉夜' ]);
- 使用 create()方法实现新增,但需要在模型端设置批量赋值的许可;
User::create([ 'username' => '辉夜', 'password' => '123', 'email' => 'huiye@163.com', 'details' => '123', ]);
//许可批量赋值,默认不可
protected $fillable = [ 'username', 'password', 'email', 'details' ];
//不许可的批量赋值,不可和$fillable 同时使用
//protected $guarded = ['uid'];
//如果取消批量赋值限制,直接如下
protected $guarded = [];
PS:必须在模型中定义批量赋值的可填充字段,否则无法生效;防止用户不小心设置新值;
- 使用 delete()方法,可以删除数据;
$users = User::find(332);
$users->delete();
//批量删除
$users = User::where('username', '夜辉');
$users->delete();
- 如果你是通过主键 id 删除,那使用 destroy(id)方法,免去查询操作;
//通过主键删除
User::destroy(328);
// 批量删除
User::destroy([1,2,3]);
转载:https://blog.csdn.net/weixin_44827418/article/details/116766461
查看评论