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();
$user = new User; // save方法第二个参数为更新条件 $user->save([ 'name' => 'thinkphp', 'email' => 'thinkphp@qq.com' ],['id' => 1]);
$user = new User; // 过滤post数组中的非数据表字段数据 $user->allowField(true)->save($_POST,['id' => 1]);
$user = new User(); // post数组中只有name和email字段会写入 $user->allowField(['name','email'])->save($_POST, ['id' => 1]);
$user = new User; $list = [ ['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'], ['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com'] ]; $user->saveAll($list);
User::where('id', 1) ->update(['name' => 'thinkphp']);
// 实例化模型 $user = new User; // 显式指定更新数据操作 $user->isUpdate(true) ->save(['id' => 1, 'name' => 'thinkphp']);
$user = User::get(1); $user->name = 'thinkphp'; // 显式指定当前操作为新增操作 $user->isUpdate(false)->save();
3.刪除資料
3.1刪除目前模型$user = User::get(1); $user->delete();
User::destroy(1); // 支持批量删除多个数据 User::destroy('1,2,3'); // 或者 User::destroy([1,2,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;
// 根据主键获取多个数据 $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; }
// 获取某个用户的积分 User::where('id',10)->value('score'); // 获取某个列的所有值 User::where('status',1)->column('name'); // 以id为索引 User::where('status',1)->column('name','id');
以上是Thinkphp框架對資料庫的操作(總結)的詳細內容。更多資訊請關注PHP中文網其他相關文章!