在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();