[Dbix-class] update_or_insert from hash reference

Matt S Trout dbix-class at trout.me.uk
Tue May 23 21:30:52 CEST 2006


Fernan Aguero wrote:
> +----[ Matt S Trout <dbix-class at trout.me.uk> (23.May.2006 15:55):
> |
>
> [ snipped ]
>
> | >my $userHashRef = { 
> | >  user_id   => $user_id,
> | >  username  => $username, 
> | >  firstname => $firstname,
> | >  ... };
> | >  
> | >my $dbix = MyApp::DB->connect( 'dbi:mysql:dbname=... );
> | >
> | >my $resultSetObj = $dbix->resultset('Users')->search( $userHashRef );
> | >
> | >$resultSetObj->update_or_create;
>
> [snipped]
>
> | >When running the script I stepped into this:
> | >DBIx::Class::ResultSet::update_or_create(): Error executing
> | >'INSERT INTO users (firstname, ..., user_id, username)
> | >VALUES (?, ?, ...) ('Fernan', ..., '1', 'fernan'):
> | >DBD::mysql::st execute failed: Duplicate entry '1' for key 1
> | >at /usr/local/lib/perl5/site_perl/5.8.8/DBIx/Class/Storage/DBI.pm
> | >line 525.
> | >
> | >Why is it trying to INSERT when it should have UPDATED the
> | >row? 
>
> [ snipped ]
>
> | my $user = $dbix->resultset('Users')->update_or_create($hashref);
> | 
> | :)
> |
> +----]
>
> Thanks Matt. That did it. 
>
> Now that I read the docs again, the description of
> update_or_create in ResultSet clearly says that it will
> 'search first ...'  (I even quoted it in my previous
> message!) but on first read this implicit search was not
> obvious to me.
>
> For some reason, my head insisted on trying to impose the
> logic of the process (which in my head was 'search' first
> and then 'update_or_create').
If you fancy having a go at writing some more examples for the Manual 
that would have made this clear to you first time round, we'd be happy 
to have them :)



More information about the Dbix-class mailing list