CakePHP 3.0: How to do an insert on duplicate key update?

泄露秘密 提交于 2019-12-04 07:42:11

You can use the query epilog() method

foreach ($articles AS $article) {
  $query = $this->Articles->query();
  $query
    ->insert($required_article_fields)
    ->values($article)
    ->epilog('ON DUPLICATE KEY UPDATE field=field+1')
    ->execute();
}

you can also pass a QueryExpression object to the method if you need to safely pass values.

Kim Stacks

As suggested by https://stackoverflow.com/a/26590483/80353

you can do

$query = $this->Articles->query();
$query->insert($required_article_fields);


// need to run clause('values') AFTER insert()
$valuesExpression = $query->clause('values')->values($articles);

$query->values($valuesExpression)
      ->epilog('ON DUPLICATE KEY UPDATE `field1`=VALUES(`field1`) ... ')
      ->execute();

I didn't fill in all the fields you want to update because I don't know which field is part of your unique index.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!