开发文档 v2.x

批量替换(replaceMany)

更新时间:2024年4月19日 22:50 浏览:301

批量替换多个对象或数组到数据库

public function replaceMany(string $table, array $objects): int

参数:

  • string $table - 表名
  • array $objects - 要替换数据库的对象数组或二维数组,对象属性或数组键名需要和该表字段一致

返回值:

  • int - 影响的行数,如果数据无变化,则返回0,失败时抛出异常

 

对象数组形式:

$objs = [];

$obj1 = new stdClass();
$obj1->name = '马云';
$obj1->age = 50;
$objs[] = $obj1;

$obj2 = new stdClass();
$obj2->name = '刘强东';
$obj2->age = 40;
$objs[] = $obj2;

$effectRows = Be::getDb()->replaceMany('user', $objs);

将编译 SQL

REPLACE INTO `user` (`name`, `age`) VALUES (?, ?);

再循环注入多行数据

['马云', '50'];
['刘强东', '40'];

 

数组形式:

$arrays = [];

$arrays[] =  [
    'name' => '马云',
    'age' => 50,
];

$arrays[] =  [
    'name' => '刘强东',
    'age' => 40,
];

$effectRows = Be::getDb()->replaceMany('user', $arrays);

 

导航