03
2023
08

thinkphp6模型:三:新增

模型数据的新增和数据库的新增数据有所区别,数据库的新增只是单纯的写入给定的数据,而模型的数据写入会包含修改器、自动完成以及模型事件等环节。

通过数组添加数据

示例是批量新增,所以$data是二维数组,增加单个数据只要换成一维数组就行了,另外,不要在同一个实例里面多次新增数据,如果确实需要多次新增,可以使用后面的静态方法处理。

<?phpnamespace app\controller;use app\model\Employees;class DbTest{   
 public function index()    {        $data=[
            [                'employee_id'  =>  96,                
            'first_name'   =>  '鸡哥',                
            'last_name'    =>  'aa'
            ],
            [                'employee_id'  =>  95,                
            'first_name'   =>  '超哥',                
            'last_name'    =>  'cc'
            ]
        ];        $res=new Employees();        return $res->saveAll($data);
    }
}

在这里插入图片描述在这里插入图片描述

replace写入

save方法可以支持replace写入:

<?phpnamespace app\controller;use app\model\Employees;class DbTest{ 
   public function index()    
{        $data=[           
 'employee_id'  =>  94,           
 'first_name'   =>  '李四',         
   'last_name'    =>  'ab'
        ];        $res=new Employees();        return $res->replace()->save($data);
    }
}

获取自增ID

这里其实获取自增ID就是获取模型的主键,如果你的主键不是id,而是employee_id的话,其实获取自增ID就变成这样:

<?phpnamespace app\controller;use app\model\Employees;class DbTest{    
public function index()    {        $data=[           
 'first_name'   =>  '王五',           
  'last_name'    =>  'df'
        ];       
         $res=new Employees();       
         $res->replace()->save($data);   
              return $res->employee_id;
    }
}

在这里插入图片描述在这里插入图片描述

静态方法

还可以直接静态调用create方法创建并写入

<?phpnamespace app\controller;use app\model\Employees;class DbTest{   
 public function index()    {//        貌似create方法不支持批量添加数据
//        $data=[//            [//           
     'first_name'   =>  '赵六',
//                'last_name'    =>  'db'//            ],//    
        [//                'first_name'   =>  '麻子',//               
         'last_name'    =>  'cs'//            ]//        ];
        $data=[            'first_name'   =>  '赵六',           
         'last_name'    =>  'db'
        ];        $res = Employees::create($data);        return $res;
    }
}

在这里插入图片描述在这里插入图片描述
create方法默认会过滤不是数据表的字段信息,可以在第二个参数可以传入允许写入的字段列表,同时也支持replace操作,使用下面的方法:

<?phpnamespace app\controller;use app\model\Employees;class DbTest{   
 public function index()    {  
      $data=[            'first_name'   =>  '麻子',            'last_name'    =>  'cs'
        ];        // 第二个参数是允许写入的字段,第三个参数是使用replace操作。
        $res = Employees::create($data,['first_name', 'last_name'],true);   
             return $res;
    }
}

在这里插入图片描述在这里插入图片描述

总结

新增数据的最佳实践原则:使用create方法新增数据,使用saveAll批量新增数据


« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。