TP框架对数据库的操作
1.添加数据
1.1添加一条数据
$user = new User; $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->save();
$user = new User; $user->save([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]);
1.2过滤非数据表字段的数据
$user = new User; // 过滤post数组中的非数据表字段数据 $user->allowField(true)->save($_POST);
1.3指定某些字段数据
$user = new User; // post数组中只有name和email字段会写入 $user->allowField(['name','email'])->save($_POST);
1.4添加多条数据
$user = new User; $list = [ ['name'=>'thinkphp','email'=>'thinkphp@qq.com'], ['name'=>'onethink','email'=>'onethink@qq.com'] ]; $user->saveAll($list);
1.5静态方法
$user = User::create([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ]); echo $user->name; echo $user->email; echo $user->id; // 获取自增ID
2.更新数据
2.1查找并更新
$user = User::get(1); $user->name = 'thinkphp'; $user->email = 'thinkphp@qq.com'; $user->save();
2.2直接更新数据
$user = new User; // save方法第二个参数为更新条件 $user->save([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ],['id' => 1]);
2.3 过滤非数据表字段
$user = new User; // 过滤post数组中的非数据表字段数据 $user->allowField(true)->save($_POST,['id' => 1]);
2.4指定某些字段
$user = new User(); // post数组中只有name和email字段会写入 $user->allowField(['name','email'])->save($_POST, ['id' => 1]);
2.5批量更新数据
$user = new User; $list = [ ['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'], ['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com'] ]; $user->saveAll($list);
2.6静态方法
User::where('id', 1)
->update(['name' => 'thinkphp']);
2.7自动识别
2.7.1显示更新数据
// 实例化模型 $user = new User; // 显式指定更新数据操作 $user->isUpdate(true) ->save(['id' => 1, 'name' => 'thinkphp']);
2.7.2显示新增数据
$user = User::get(1); $user->name = 'thinkphp'; // 显式指定当前操作为新增操作 $user->isUpdate(false)->save();
3.删除数据
3.1删除当前模型
$user = User::get(1); $user->delete();
3.2根据主键删除
User::destroy(1); // 支持批量删除多个数据 User::destroy('1,2,3'); // 或者 User::destroy([1,2,3]);
3.3条件删除
User::destroy(function($query){ $query->where('id','>',10); });
4.查询数据
4.1获取单个数据
// 取出主键为1的数据 $user = User::get(1); echo $user->name; // 使用查询构造器查询满足条件的数据 $user = User::where('name', 'thinkphp')->find(); echo $user->name;
4.2获取多个数据
// 根据主键获取多个数据 $list = User::all('1,2,3'); // 或者使用数组 $list = User::all([1,2,3]); // 对数据集进行遍历操作 foreach($list as $key=>$user){ echo $user->name; }
// 使用查询构造器查询 $list = User::where('status', 1)->limit(3)->order('id', 'asc')->select(); foreach($list as $key=>$user){ echo $user->name; }
4.3获取某个字段或者某个列的值
// 获取某个用户的积分 User::where('id',10)->value('score'); // 获取某个列的所有值 User::where('status',1)->column('name'); // 以id为索引 User::where('status',1)->column('name','id');