开启辅助访问
帐号登录 |立即注册

TP5用模型来更新数据表中的数据:sava()/savaAll()/update()操作

 
1、Update更新数据

save($data=[],$where=[])     单条更新
调用方式:实例化
saveAll($data=[],true)     批量更新
调用方式:实例化
update($data=[],$where=[],$field=[])     单条更新
调用方式:静态
模型对象
1、不允许无条件更新,必须设置更新条件;
2、可以将更新条件,如主键写在更新数据中,方法可以自动认别;
3、更新条件可以使用闭包,完成更复杂的业务逻辑。
举例:
<?php
namespace app\ index\ controller ;
use app\ index \model\Staff;
class Index
{
public function index( )
{
$staff = new Staff();
$data =[
name '=> '天山童姥',
' age '=>80
];
$where =[' id'=>1032,] ;
$staff->save ($data,$where) ;
dump ($staff->getData());
}
}


如果没有设置更新条件where,需要用 isUpdate(true),说明不是插入,是更新数据。举例:
<?php
namespace app\ index\controller;
use app\ index\model\Staff;
class Index
{
public function index( )
{
$staff = new Staff();
$data =[
id'=>1032 ,
name'=> '岳不群',
age '=>80
];
$staff-> isUpdate(true)->save($data);
dump( $staff->getData());
}



使用::update()静态方法更新
<?php
namespace app\ index\controller ;
use app\ index \model\Staff ;
class Index
{
public function index( )
//update(更新数据,更新条件,允许更新的字段)
$data =[
'name'=>'韦-笑', 'age'=>59, ' salary'=>5600
];
$where = [ ' id'=>1036] ;
$field = ['name' , ' age '] ;
$result = Staff: :update ( $data, $where,$field);
dump ($result->getData());
}
}



使用闭包来设置查询条件
<?php
namespace app\ index\ controller ;
use app\ index\model\Staff ;
class Index
{
public function index()
//update(更新数据,更新条件,允许更新的字段)
$data =[
name '=>'韦一笑','age'=>59,' salary'=>5600
];
$where = function ($query){
$query->where( 'id' ,1036);
};
$field=['name',‘age' , 'salary'];
$result = Staff::update($data, $where,$field) ;
dump ( $result->getData());
}
}
如在闭包中使用外部变量,要用use关键字调用变量
$id = 1036 ;
$where = function ($query) use ($id) {
$query->where( 'id',$id);
};



回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

友情链接
  • 艾Q网

    提供设计文章,教程和分享聚合信息与导航工具,最新音乐,动漫,游戏资讯的网站。