I use this strategy to check for unique constraints after flush (), maybe not the way you want, but may help someone else.
When you call flush () if a unique constraint cannot fail, a PDOException is thrown with code 23000 .
try { // ... $em->flush(); } catch( \PDOException $e ) { if( $e->getCode() === '23000' ) { echo $e->getMessage(); // Will output an SQLSTATE[23000] message, similar to: // Integrity constraint violation: 1062 Duplicate entry 'x' // ... for key 'UNIQ_BB4A8E30E7927C74' } else throw $e; }
If you need to get the column name with an error :
Create indexes on tables with prefix names, for example. 'Unique _'
* @Entity * @Table(name="table_name", * uniqueConstraints={ * @UniqueConstraint(name="unique_name",columns={"name"}), * @UniqueConstraint(name="unique_email",columns={"email"}) * })
DO NOT indicate your columns as unique in the @Column definition
This seems to override the index name with random ...
**ie.** Do not have 'unique=true' in your @Column definition
After regenerating the table (you may have to drop it and rebuild it), you can extract the column name from the exception message.
// ... if( $e->getCode() === '23000' ) { if( \preg_match( "%key 'unique_(?P<key>.+)'%", $e->getMessage(), $match ) ) { echo 'Unique constraint failed for key "' . $match[ 'key' ] . '"'; } else throw $e; } else throw $e;
Not perfect, but it works ...
Peter Johnson May 22 '11 at 19:56 2011-05-22 19:56
source share