上次已经把项目和数据库对接上并且用model模型实现数据表单条数据的添加,如下:
<?php namespace app\admin\controller; use app\admin\model\Admin;//引用Admin模型 class Datatest { public function index() { return '这里是数据测试链接'; } public function add(){ //通过原生方法向数据表添加数据 // $admin = new Admin;//实例化模型 // $admin -> save([//利用save()方法向数据表添加数据,此方法只能向已有字段添加数据,一般返回 // 'typename' => '超级管理员', // 'mobile' => '13878298210', // 'email' => '483427581@qq', // 'password' => '123456', // 'realname' =>'胡一可', // 'lastip' =>'192.168.1.1' // ]); //通过静态方法添加数据 $admin = Admin::create([ 'typename' => '超级管理员', 'mobile' => '13367521211', 'email' => '483427581@qq', 'password' => '123456', 'realname' =>'罗志详', 'lastip' =>'192.168.1.1' ]); } }
1.批量添加数据
saveAll()可以实现批量添加数据
public function addall(){ $admin = new Admin; $datalist = [ ['typename' => '超级管理员','mobile' => '13367521222','email' => '483427581@qq','password' => '123456','realname' =>'马化腾','lastip' =>'192.168.1.1'], ['typename' => '超级管理员','mobile' => '13367521222','email' => '483427581@qq','password' => '123456','realname' =>'码云','lastip' =>'192.168.1.1'], ['typename' => '超级管理员','mobile' => '13367521222','email' => '483427581@qq','password' => '123456','realname' =>'bat','lastip' =>'192.168.1.1'], ['id' => '2','typename' => '普通管理员','mobile' => '13367521222','email' => '483427581@qq','password' => '123456','realname' =>'蒙恰恰','lastip' =>'192.168.1.1'] ]; $admin->saveAll($datalist);//利用saveAll()实现批量上传数据,当数据中含有主键时会被认为是更新操作 }
2.数据查找
public function find(){ //$admin = Admin::find(2);//直接通过主键查询数据 //$admin = Admin::where('mobile','13878298210') -> find();//通过where条件查询 //$admin = Admin::where('id','>','3') -> select();//通过where条件查询 //$admin = Admin::select();//查询全部数据 //$admin = Admin::select([1,2,3]);//多条数据查询 return $admin; }
3.数据更新
public function update(){ $admin = Admin::find(3);//先查找数据 $admin->mobile = '15977291627';//修改数据1 $admin->realname = '蒙66';//修改数据2 $admin->save();//用save()保存数据 return $admin; }
4.数据删除
public function delete(){ //方法一 // $admin = Admin::find(12);//先查找数据 // $admin->delete();//直接删除 //静态方法 $admin = Admin::destroy(11);//返回的是布尔值 //条件删除 // $admin = Admin::where('id','>','8')->delete(); }
先到这吧~