spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer
http://phpdatamapper.com
BSD 3-Clause "New" or "Revised" License
601 stars 101 forks source link

upsert not works as expect if exist update then insert #224

Open tablecell opened 7 years ago

tablecell commented 7 years ago

field uid without unique index

CREATE TABLE contact ( id int(10) unsigned NOT NULL AUTO_INCREMENT, uid int(255) NOT NULL, address varchar(255) COLLATE utf8_unicode_ci DEFAULT '') ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

 $mapper = $spot->mapper('Entity\Contact');
  //$mapper->migrate();
   $mapper->upsert(['address'=>'xxx'],['uid'=>14]);

nothing happened

 $mapper->upsert(['uid'=>14','address'=>'xxx'],['uid'=>14]);

add new row with (id=5,uid=14, address=xxx)

repeat

 $mapper->upsert(['uid'=>14','address'=>'xxx'],['uid'=>14]);

add new row with (id=6,uid=14, address=xxx)

  $mapper->upsert(['address'=>'yyyy'],['uid'=>14]);

(id=5,uid=14, address=xxx) changed to (id=5,uid=14, address=yyyy )


field uid with unique index CREATE TABLE contact ( id int(10) unsigned NOT NULL AUTO_INCREMENT, uid int(255) NOT NULL, address varchar(255) COLLATE utf8_unicode_ci DEFAULT , UNIQUE KEY uid (uid)

) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

   $mapper->upsert(['address'=>'aaaa'],['uid'=>24]);

nothing happened

  $mapper->upsert(['uid'=>24,'address'=>'aaaa'],['uid'=>24]);

add new row (id=7,uid=24,address=aaaa)

repeat

  $mapper->upsert(['uid'=>24,'address'=>'aaaa'],['uid'=>24]);

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '24' for key 'uid'' in

  $mapper->upsert([ 'address'=>'bbbb'],['uid'=>24]);

(id=7,uid=14, address=aaaa) changed to (id=7,uid=24, address=bbbb )

conclusion: if first param $data include uid then insert new record first param $data exclude uid then update record

not automatic as expect

willemwollebrants commented 7 years ago

Check your entity definition. You probably forgot to mark 'uid' as a unique field there:

class Contact extends Spot\Entity
{
    protected static $table = 'contact';

    public static function fields()
    {
        return [
            'id' => ['type' => 'integer', 'primary' => true, 'autoincrement' => true],
            'uid' => ['type' => 'integer', 'default' => 0, 'unique' => true],
            'address' => ['type' => 'text']
        ];
    }
}