Thinkphp5.0第三篇
Posted 陈国松
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thinkphp5.0第三篇相关的知识,希望对你有一定的参考价值。
批量插入数据
//新增一条数据的方法
public function add()
{
/*$user =new UserModel();
$user->id=1;
$user->name='陈国松';
$user->email='liuyun@qq.com';
$user->birthday=strtotime('1989-7-11');
if( $user->save()){
return '用户新增成功';
}else{
return '用户新增失败';
}*/
$user['name']='看云';
$user['email']='kanyun@qq.com';
$user['birthday']=strtotime('1991-6-12');
if($result=UserModel::create($user)){
return '新增成功';
} else{
return '新增失败';
}
}
//批量新增数据
public function addList(){
$user=new UserModel();
$list=[
['name'=>'张三','email'=>'zhangsan@qq.com','birthday'=>strtotime('1978-8-9')],
['name'=>'李四','email'=>'lisi@qq.com','birthday'=>strtotime('1977-8-9')],
];
if( $user->saveAll($list)){
return '批量插入成功';
}else{
return '批量插入失败';
}
}
模型操作之更新数据
查找并更新
$user=UserModel::get(1);
$user->name='陈松';
$user->email='chensong@qq.com';
$user->save();
if($user->save()){
return '成功';
}else{
return '失败';
}
直接更新数据
$user=new UserModel();
$user->save(['name'=>'刘涛','email'=>'liutao@qq.com'],['name'=>'陈国松']);
批量更新
$user =new UserModel();
$list=[
['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'],
['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com']
] ;
$user->isUpdate()->saveAll($list);
数据库类更新数据
$user = new UserModel;
$user->where('name', '刘涛')->update(['name' => 'thinkphp']);
静态方法
UserModel::where('name','thinkphp')->update(['name'=>'陈国松','email'=>'chenguosong@qq.com','birthday'=>strtotime('1997-9-16')]);
查询
取出主键为1的数据
$user=UserModel::get(1);
dump($user);
echo $user->name.'</br>'.$user->email.'</br>';
使用数组查询
$user =UserModel::get(['name'=>'陈国松']);
echo $user->email;
实例化模型后调用查询方法
$user=new UserModel;
$result=$user->where('name','陈国松')->find();
echo $result->name;
$user =new Usermodel;
$result=$user->where('name','陈国松')->find();
echo $result->birthday;
根据主键查询多个数据
$list=UserModel::all([1,2,3]);
foreach($list as $key=>$value){
echo $value->name.'</br>';
echo $value->birthday.'</br>';
echo $value->email.'</br>';
}
$user =new UserModel;
$result=$user->where('name','陈国松')->limit(2)->order('id','desc')->select();
foreach($result as $key=>$value){
echo $value['name'].'</br>';
echo $value['email'].'</br>'; }
聚合
聚合函数的调用
$user=new UserModel;
echo $user->Count('id').'</br>';
echo $user->Max('id');
静态调用大全
User::count();
User::where('status','>',0)->count();
User::where('status',1)->avg('score');
User::max('score');
动态调用大全
$user = new User;
$user->count();
$user->where('status','>',0)->count();
$user->where('status',1)->avg('score');
$user->max('score');
以上是关于Thinkphp5.0第三篇的主要内容,如果未能解决你的问题,请参考以下文章