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 update() and save() failed when using unique constraint in DB level

Hi all,

I am trying to update a column for some record in the database, but because of there is a another unique column exists in the table, Phalcon model fails to update that record.

    $allUsers = Users::find();
    foreach ($allUsers as $user){
        $user->token = $this->someToken;
        $user->update();
    }

It returns this error:

Unique violation: 7 ERROR: duplicate key value violates unique constraint "user_name_unique"

Table structure:

   CREATE TABLE public.users
   (
      id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass),
      user_name text,
      user_job_position character varying(100),
      first_name character varying(50),
      last_name character varying(100),
       last_activity time without time zone,
      ip_address character varying(15),
      token text,
      token_hash text,
      CONSTRAINT user_name_unique UNIQUE (user_name)
   )

Am I doing something wrong ?

use the exclude option. See the code


new Uniqueness(
[
    'table' => 'public.users',
    'column' => 'user_name_unique',
    'exclude' => [
        'column' => 'id',
        'value' => 1 // here you have to exclude your ID record
    ]
]
);


7.0k
Accepted
answer
edited Feb '18

Thanks Degiovanni ,

I fixed it by defining a primary key fr user_id in the database.