Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Model does not save properly when id is reset in beforeSave() - bug or pebkac?

This is my table:

CREATE TABLE `user` (
  `id` binary(16) NOT NULL,
  `username` varchar(191) NOT NULL,
  ...
  PRIMARY KEY(`id`)
  )

My model for the table contains this:

    public function beforeSave() {
        $this->id = hex2bin($this->id);
    }
    public function afterSave() {
        $this->afterFetch();
    }

    public function afterFetch() {
        $this->id = bin2hex($this->id);
    }

When I fetch a record, afterFetch() fires properly and I see the translated id's, and upon calling save(), I do see beforeSave() changing the id back into a binary value, so everything looks fine so far. The problem is at execution, the id is actually never translated back into binary but is still a hex string, causing the Update to change no records (since there is no match), but save() to pass with no errors produced since it's a valid sql statement. (I enabled query logging in Mysql to see recently executed queries: SET GLOBAL logoutput = 'TABLE'; SET GLOBAL generallog = 'ON';) Funny thing is afterSave() is called and does show id being a binary value in the debugger, so I get the feeling that any id changes are being ignored by save() even if it's in beforeSave(). Is this a bug or am I doing something wrong?

I actually ended up sidestepping the whole issue by setting custom getters/setters for the id, but I'm unsure if this is still a bug or not.



106.1k
Accepted
answer

Primary keys just can't be changed in phalcon. This is how ORM is implemented.