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

来源:互联网 发布:最新软件代理 编辑:程序博客网 时间:2024/06/07 04:38

在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();
原创粉丝点击