静态增删改查 / 关联操作

最后更新于:2022-04-02 02:22:17

[TOC] ## 静态增删改查操作 ### 增 ``` $user = User::create([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); echo $user->email; echo $user->id; // 获取自增ID ``` ### 增or 更新 ``` //批量添加或更新 $user = new User; $list = [ ['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'], ['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com'] ]; $user->saveAll($list); //单个添加或更新 $user = new User(); $user->allowField(true)->save($_POST,['id' => 1]); $user->allowField(true)->save($_POST]); ``` ### 删 #### 根据主键删除 ``` User::destroy(1); //或 User::destroy([1,2,3]); ``` #### 条件删除 ``` User::destroy(['status' => 0]); //或 User::where('id','>',10)->delete(); ``` ### 改 #### 查找并更新 ``` $user = User::get(1); $user->name = 'thinkphp'; $user->save(); ``` #### 直接更新数据 ``` User::update(['id' => 1, 'name' => 'thinkphp']); ``` #### 复杂界面更新 ``` User::where(['status'=>1,'name'=>'cpj'])->update(['name' => 'thinkphp']); ``` #### 更新个别字段 ``` $loan = LoanModel::get($id); $loan->show_app = $loan->getData('show_app')==1?0:1; $loan->save(); ``` ### 查 #### 获取单个数据 ``` $user = User::get(1); echo $user->name; // 使用数组查询 $user = User::get(['name' => 'thinkphp']); // 使用闭包查询 $user = User::get(function($query){ $query->where('name', 'thinkphp'); }); echo $user->name; // 获取某个列的所有值 User::where('status',1)->column('name') // 以id为索引 User::where('status',1)->column('name','id'); ``` #### 获取多个数据 ``` // 或者使用数组 $list = User::all([1,2,3]); // 使用条件查询(只能对where操作) $list = User::all(['status'=>1]); //闭包 比条件查找强大 $list = User::all(function($query){ $query->where('status', 1)->limit(3)->order('id', 'asc'); }); ``` ### 一对一关联 #### 隐藏关联的数组,绑定父元素 加别名 ``` //模型中方法,注意使用return进行 public function Reloan(){ //外键id reloanModel 的外键id return $this->hasOne('ReloanModel','lid')->bind('tid'); //->bind('username'=>'name') 把name改为username } //调用 LoanModel::get(8,'reloan')->hidden(['reloan']) //hidden 先用bind绑定到父类 然后用hidden 隐藏关联表 LoanModel::all(8,'reloan')->hidden(['reloan','users']) ``` #### 更新关联表 ``` $loan = LoanModel::get(8); $loan->reloan->tid=12; $loan->reloan->save(); ```
';