Vael Victus
Vael Victus

Reputation: 4122

How To Force Insert In CakePHP?

I have a MySQL archive table with the following structure:

    `histories` 
      `uid` int(10) unsigned NOT NULL,
      `type` varchar(255) NOT NULL,
      `param` int(11) NOT NULL,
      `param2` varchar(255) NOT NULL,
      `time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
     ENGINE=ARCHIVE DEFAULT CHARSET=latin1;

I do not want to add an auto-incrementing `id' column. This table's engine is archive and it does exactly what I need it to, with this structure.

I wish to save like this:

$this->History->create();
$this->History->save(['uid' => uid, 'type' => 'deleted_entry', 'param' => $thing_id]);

But CakePHP forces an update, which I don't want and the ARCHIVE engine doesn't support. Cake seems to be looking for a primary key of uid, finding it and deciding that it should update and there seems to be no flag available to force an insert. I do not want to resort to $this->Model->query().

UPDATE: Set $primaryKey = null in AppModel. $this->create(); will then insert.

class History extends AppModel {
    public $primaryKey = null;
}

If you want to do an update after, simply:

$this->History->primaryKey = 'uid'; before the save()

Upvotes: 0

Views: 317

Answers (1)

jeremyharris
jeremyharris

Reputation: 7882

You can tell Cake 2 that you have no primary key by setting the model's $primaryKey property to null:

$this->History->primaryKey = null;
$this->History->create();
$this->History->save(['uid' => uid, 'type' => 'deleted_entry', 'param' => $thing_id]);

Upvotes: 1

Related Questions