Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use 'on duplicate key update' when saving record in CakePHP

My model has 2 unique indexes. The primary key, and an alphanumeric id.

I only have the alphanumeric id when updating said record, so I need to add an "on duplicate key update" statement to the save function, but how do I do that?

And I do not want to query for the primary key first, as that would make the import process incredibly long and slow.

like image 428
skerit Avatar asked Nov 15 '12 11:11

skerit


1 Answers

Another option is to override Model->exists() in your models. This is actually the same as Cake does it, but extended to other keys not only primaryKey.

/**
 * Overrides Model->exists() method so we can check for uniqueness if primary key is not set
 *
 * If a record already exists, sets the primary key of that record to do an update
 *
 * @param int $id
 * @return bool True if the record exists, false otherwise
 */
public function exists($id = null)
{
    if (empty($id) && !$this->getID() && isset($this->data[$this->alias]) && is_array($this->data[$this->alias])) {
        // given $id and primary key are empty, try with data
        $exists = $this->find('first', array(
            'fields' => array($this->primaryKey),
            'conditions' => array(
                'key1'=>$this->data[$this->alias]['key1'],
                'key2'=>$this->data[$this->alias]['key2'],
            ),
            'recursive' => -1,
            'callbacks' => false,
        ));
        if ($exists) {
            $this->set($this->primaryKey, $exists[$this->alias][$this->primaryKey]);
            return true;
        }
    }
    return parent::exists($id);
}
like image 175
Calin Avatar answered Sep 28 '22 09:09

Calin