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 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;

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

edited 25d ago

Thanks Degiovanni ,

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