Home >PHP Framework >ThinkPHP >How to update data in Thinkphp5 model

How to update data in Thinkphp5 model

angryTom
angryTomforward
2020-03-17 09:13:554258browse

This article pays attention to the method of updating data of Thinkphp5 model. There are two methods of updating data of thinkphp5 model. I hope it will be helpful to friends who are learning thinkphp!

How to update data in Thinkphp5 model

Thinkphp5 model’s method of updating data

ThinPHP5 model’s two methods of updating data are update, one is the save method, see the actual case code below.

<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\User;//调用模型
class Index extends Controller{
  public function index(){
    //update一般方法
    $res=User::update([
      &#39;id&#39;=>1,
      &#39;name&#39;=>&#39;lei&#39;
    ]);
    //update参数方法
    $res=User::update([
      &#39;id&#39;=>1,
      &#39;name&#39;=>&#39;lei&#39;
    ],[&#39;id&#39;=>2]);
    //update闭包函数方法
    $res=User::update([
      &#39;name&#39;=>&#39;lei&#39;
    ],function($query){
      $query->where("id","lt","3");
    });
    //update where方法 推荐使用的方法
    $res=User::where("id","<",6)
    ->update([
      &#39;name&#39;=>&#39;lei&#39;
    ]);
    //save方法
    $userModel=User::get(1);
    $userModel->name=&#39;1234&#39;;
    $res=$userModel->save();
    //new save方法
    $userModel=new User;
    $res=$userModel->save([
      &#39;name&#39;=>&#39;lei&#39;
    ],[&#39;id&#39;=>1]);
    //new save闭包函数方法,次要推荐
    $userModel=new User;
    $res=$userModel->save([
      &#39;name&#39;=>&#39;lei&#39;
    ],function($query){
      $query->where("id","<","5");
    });
    //saveAll批量更新方法
    $userModel=new User;
    $res=$userModel->saveAll([
      [&#39;id&#39;=>1,&#39;name&#39;=&#39;lei1&#39;],
      [&#39;id&#39;=>2,&#39;name&#39;=&#39;lei2&#39;]
    ]);
    dump($res);
  }
 }

PHP Chinese website, a large number of ThinkPHP tutorials, welcome to learn!

The above is the detailed content of How to update data in Thinkphp5 model. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.100txy.com. If there is any infringement, please contact admin@php.cn delete