28684ad9e51bacaf931bdbbce4c7af96ca8216a7
3 namespace Civi\Api4\Generic
;
6 * Update one or more records with new values.
8 * Use the where clause (required) to select them.
10 class DAOUpdateAction
extends AbstractUpdateAction
{
11 use Traits\DAOActionTrait
;
14 * Criteria for selecting items to update.
16 * Required if no id is supplied in values.
20 protected $where = [];
25 public function _run(Result
$result) {
26 // Add ID from values to WHERE clause and check for mismatch
27 if (!empty($this->values
['id'])) {
28 $wheres = array_column($this->where
, NULL, 0);
29 if (!isset($wheres['id'])) {
30 $this->addWhere('id', '=', $this->values
['id']);
32 elseif (!($wheres['id'][1] === '=' && $wheres['id'][2] == $this->values
['id'])) {
33 throw new \
Exception("Cannot update the id of an existing " . $this->getEntityName() . '.');
37 // Require WHERE if we didn't get an ID from values
39 throw new \
API_Exception('Parameter "where" is required unless an id is supplied in values.');
42 // Update a single record by ID unless select requires more than id
43 if ($this->getSelect() === ['id'] && count($this->where
) === 1 && $this->where
[0][0] === 'id' && $this->where
[0][1] === '=' && !empty($this->where
[0][2])) {
44 $this->values
['id'] = $this->where
[0][2];
45 $result->exchangeArray($this->writeObjects([$this->values
]));
49 // Batch update 1 or more records based on WHERE clause
50 $items = $this->getObjects();
51 foreach ($items as &$item) {
52 $item = $this->values +
$item;
56 throw new \
API_Exception('Cannot ' . $this->getActionName() . ' ' . $this->getEntityName() . ', no records found with ' . $this->whereClauseToString());
59 $result->exchangeArray($this->writeObjects($items));