Home > Article > PHP Framework > How to add data to Thinkphp5 model
This article introduces two methods for adding data to models in thinkphp5. I hope it will be helpful to friends who are learning thinkphp!
Thinkphp5 model method of adding data
ThinPHP5 model has two methods of adding data, one is create, one is the save method, see the actual case code below.
<?php namespace app\index\controller; use think\Controller; use app\index\model\User; public function index(){ //create方法添加数据 $res=User::create([ 'name'=>'lei', 'email'=>'leixiaotian@163.com', 'password'=>'123' ],true);//true排除掉表中不存在的字段 dump($res->id); dump($res); //save方法添加 $userModel=new User; $userModel->name='lei'; $userModel->email='leixiaotian@163.com'; $userModel->save(); dump($userModel->id); //sava数组方法 $res=$userModel->save([ 'name'=>'lei', 'email'=>'leixioatian@163.com' ]); dump($res); //sava允许字段方法 $userModel=new User; $res=$userModel ->allowField(['name']) ->save([ 'name'=>'lei', 'email'=>'leixioatian@163.com' ]); dump($res); //sava保存多条数据 $userModel=new User; $res=$userModel->saveAll([ ['name'=>'lei'], ['name'=>'lei'] ]); foreach ($res as $val) { dump($val->toArray()); } } }
Recommended learning: thinkphp tutorial
The above is the detailed content of How to add data to Thinkphp5 model. For more information, please follow other related articles on the PHP Chinese website!