thinkPHP使用模型更新数据

一.用模型静态方法:update([更新数组],[更新条件])

1.更新条件用数组给出

public function test()
{
//$res = $this->data->getMenu();
//获取模型对象
$model = new Data();
$res = Data::update([
'node_name' => 'hahahaa',
'typeid' => 44,
], ['id' => 11]);
dump($res);
}

2.更新函数用闭包函数给出

public function test()
{
//$res = $this->data->getMenu();
//获取模型对象
$model = new Data();
$res = Data::update([
'node_name' => 'ge',
], function ($query) {
$query->where([
'id' => ['>', 11],
'typeid' => ['BETWEEN', [13, 20]],
]);
});
dump($res);
}
闭包函数通常只用来生成复杂的查询条件,参数只有一个,$query就是查询类实例对象
 
二.用模型直接调用Db类方法
三.模型的save()方法:
能将模型中的数据写入到表的对应字段中,所以用save()方法更新表中数据,第一步就是获取表中需要更新的数据,即初始化当前数据模型
1.用模型中的数组去更新字段
public function test()
{
//$res = $this->data->getMenu();
//获取更新数据,初始化模型对象,读取主键
$data = Data::get(11);
//更新数据模型
$data->node_name = '李达康';
$data->typeid = 4;
//将模型数据写入对应的字段中
$res = $data->save();

//等价于
// $res=$data->save([
// 'node_name'=>'李达康',
// 'typeid'=>4
// ]);
//返回受影响的记录数int(1)
dump($res);
}
 
//对于复杂的条件,可以用闭包来构造查询表达式
public function test()
{
//$res = $this->data->getMenu();
$model = new Data();
$res = $model->save([
'node_name' => 'jjjj',
], function ($query) {
$query->where('id', 'GT', 10)
->where('typeid', 'LT', '18');
});
dump($res);
}
 
三.模型动态调用saveAll(二维关联数组):同时更新多个记录
saveAll()只需传一个参数数组,数组中的每一个元素又是一个与表字段对应的关联数组
public function test()
{
//$res = $this->data->getMenu();
$model = new Data();
$res = $model->saveAll([
['id' => 1, 'node_name' => '我是一'],
['id' => 2, 'node_name' => '我是二'],
]);
dump($res);
}
 
 
原文地址:https://www.cnblogs.com/ymdphp/p/10950255.html