Saving a model without data

Published on and tagged with cakephp  model

Yesterday, I created a table which doesn’t contain any custom columns, i.e. it contains only the columns “id”, “created”, and “modified”:

CREATE TABLE users (
  id INT(11) NOT NULL AUTO_INCREMENT,
  created DATETIME,
  modified DATETIME,
  PRIMARY KEY (id)
);

The corresponding model is pretty simple:

class User extends AppModel {}

Even though this is probably one if the simplest models you can have, it is not possible to save it with the save() method of the model. The method returns “success”, but no record is written to the database:

$this->User->create();
if ($this->User->save()) {
    echo 'save successful';
} else {
    echo 'save failed';
}

My second approach was to manually set the id to null. This created a new record, but it left the “created” and “modified” columns untouched:

$this->data['User']['id'] = null;
$this->User->create();
if ($this->User->save($this->data)) {
    echo 'save successful';
} else {
    echo 'save failed';
}

As a workaround I wrote the following method in my model:

function createUser() {
    $this->query('INSERT INTO '.$this->table.' (modified, created) VALUES (now(), now())');
    $data = $this->query('SELECT LAST_INSERT_ID() AS insertID');

    return $data[0][0]['insertID'];
}

Maybe it helps someone else until this bug gets fixed.

4 comments baked

  • The Mullet

    I don’t get the idea why you tried this in the first place: creating an entry just to see when you did it ?

  • cakebaker

    @The Mullet: Thanks for your question!

    The reason I use such a table is that a User can have multiple OpenIDs to login, i.e. multiple OpenIDs are tied to one user account.

    I hope with this short explanation it is more clear what the idea is ;-)

  • Abba Bryant

    I have run into this before ( quite some time ago ) but if I remember correctly – I simply added a field that I never needed a value in to the table. I made sure I didn’t require a value for it in any validation and defaulted it to null.

    That worked for me. YMMV.

  • cakebaker

    @Abba: Thanks for your comment, and yes, that is a possible solution. Personally, I don’t like it to add such a dummy field to a table to avoid a bug in the used framework…

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License