We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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 log_output = 'TABLE'; SET GLOBAL general_log = '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?



1.0k

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.



145.0k
Accepted
answer

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