CakePHP中的批量保存及批量更新

在CakePHP中,批量保存及批量更新主要用到 Cake\ORM\Table::newEntities(array $data, array $options[])Cake\ORM\Table::patchEntities(array|Traversable $entities , array $data , array $options[])Cake\ORM\Table::saveMany(array|Cake\ORM\ResultSet $entities , array|ArrayAccess $options[]) 等方法;

批量保存

假如有一张 articles 数据表,其中有 id title content published等字段,那么在ArticlesController的方法中进行批量保存,代码大致如下:

//数组数据
$data = [
    [
        'title' => 'First Article',
        'content' => 'This is the first article.',
        'published' => 1
    ],
    [
        'title' => 'Second Article',
        'content' => 'This is the second article.',
        'published' => 1
    ],
    ...
];
//批量保存
$entities = $this->Articles->newEntities($data);
$rows = $this->Articles->saveMany($entities); //返回批量保存的条数

批量更新

假如要把所有title中包含Article的文章下线('published' => 0),则在ArticlesController的方法中:

//查询需要更新的数据
$articles = $this->Articles->find('all', [
    'conditions' => [
        'title LIKE' => "%Article%"
    ]
]);
//设置更新后的值
foreach($articles as $article) {
    $data[] = array(
        'id' => $article->id, //必须,用主键id进行识别
        'published' => 0
    );
}
//批量更新
$articles = $this->Articles->patchEntities($articles, $data);
$rows = $this->Articles->saveMany($articles); //返回批量更新的条数

批量更新还可以使用如下两种方式:

$this->Articles->updateAll(
    ['published' => 0], //需要更新的字段值
    ['title LIKE' => '%Article%'] //查询条件
);

$this->Articles->query()
               ->update()
               ->set(['published' => 0])
               ->where(['title LIKE' => '%Article%'])
               ->execute();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值