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

How to update data in Thinkphp5 model

angryTom
Release: 2020-03-17 09:13:55
forward
4265 people have browsed it

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);
  }
 }
Copy after login

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!

Related labels:
source:www.100txy.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template