Spot\Mapper::upsert PHP Method

upsert() public method

Upsert save entity - insert or update on duplicate key. Intended to be used in conjunction with fields that are marked 'unique'
public upsert ( array $data, array $where ) : object
$data array array of key/values to set on new Entity instance
$where array array of keys to select record by for updating if it already exists
return object Instance of $entityClass with $data set on it
    public function upsert(array $data, array $where)
    {
        $entityClass = $this->entity();
        $entity = new $entityClass($data);
        $result = $this->insert($entity);
        // Unique constraint produces a validation error
        if ($result === false && $entity->hasErrors()) {
            $dataUpdate = array_diff_key($data, $where);
            $existingEntity = $this->first($where);
            if (!$existingEntity) {
                return $entity;
            }
            $existingEntity->data($dataUpdate);
            $entity = $existingEntity;
            $result = $this->update($entity);
        }
        return $entity;
    }

Usage Example

Example #1
0
 public function hookUpdateSearchIndex(\Spot\Mapper $mapper)
 {
     $result = $mapper->upsert('Entity_Event_Search', array('event_id' => $this->id, 'body' => $this->title . ' ' . $this->description), array('event_id' => $this->id));
 }