phpormpropelpropel2

Propel validation for unique key pair


In my database user_group table UNIQUE_KEY consist of two columns , user_id and user_group_id. This is how it looks like in propel schema :

<unique name="UNIQUE_KEY">
            <unique-column name="user_id"/>
            <unique-column name="user_group_id"/>
</unique>

If it is about one column then you can set validation behavior like below :

<behavior name="validate">
     <parameter name="rule1"
     value="{column: column_name, validator: Unique, options {message:Your validation message here.}}"/>
</behavior>

So what I wanted to know is how to set unique validation for key pair user_id and user_group_id. Is there any possibility to pass an array of column_names ?? Any suggestions will be appreciable. Thank you .


Solution

  • This features is not available yet, but you have a few options:

    1. Handle the duplicates yourself:

    // First check for a duplicate
    $duplicates = TableAQuery::create()
      ->filterByKey1($key1)
      ->filterByKey2($key2)
      ->count();
    
    if ($duplicates>0) {
        throw new \PropelException('Row already exists');
    }
    // No duplicate, add the new row
    

    2. Handle the underlying duplicate Databases's INSERT INTO violation via try-catch:

     try{
         $obj->save();
     } catch (PropelException $e) {
         if (stripos($e->getMessage(), ' duplicate key ') !== false) {
             throw new \PropelException('Row already exists');
         }
     }
    

    Option 2 might be less painful if performance is an issue as it saves you a query, but may increase your auto_increment (esp. on MySQL) if have not configured it to ignore duplicate inserts.