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');
相關文章
相關標籤/搜索