Thinkphp框架对数据库的操作(总结)
时间:2020-01-29 14:08
1.添加数据 1.1添加一条数据 1.2过滤非数据表字段的数据 1.3指定某些字段数据 1.4添加多条数据 1.5静态方法 2.更新数据 2.1查找并更新 2.2直接更新数据 2.3 过滤非数据表字段 2.4指定某些字段 2.5批量更新数据 2.6静态方法 2.7自动识别 2.7.1显示更新数据 2.7.2显示新增数据 3.删除数据 3.1删除当前模型 3.2根据主键删除 3.3条件删除 4.查询数据 4.1获取单个数据 4.2获取多个数据 4.3获取某个字段或者某个列的值 更多相关ThinkPHP知识,请访问ThinkPHP教程! 以上就是Thinkphp框架对数据库的操作(总结)的详细内容,更多请关注gxlsystem.com其它相关文章!$user = new User;
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save();
$user = new User;
$user->save([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
]);
$user = new User;
// 过滤post数组中的非数据表字段数据
$user->allowField(true)->save($_POST);
$user = new User;
// post数组中只有name和email字段会写入
$user->allowField(['name','email'])->save($_POST);
$user = new User;
$list = [
['name'=>'thinkphp','email'=>'thinkphp@qq.com'],
['name'=>'onethink','email'=>'onethink@qq.com']
];
$user->saveAll($list);
$user = User::create([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
]);
echo $user->name;
echo $user->email;
echo $user->id; // 获取自增ID
$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();
$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);
});
// 取出主键为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');