防止Propel插入空字符串

时间:2013-04-25 10:29:28

标签: php mysql propel

如果未设置列,我如何阻止Propel ORM插入空字符串?

CREATE TABLE user (  
  uid INTEGER PRIMARY KEY AUTO_INCREMENT,  
  email VARCHAR(255) NOT NULL UNIQUE,  -- No default value
  ...  
) Engine InnoDB ... ;  

Propel允许$user = new User(); $user->save();。 我尝试过设置SQL_MODE,但没有帮助。

2 个答案:

答案 0 :(得分:2)

执行此操作的正确方法是使用架构中的验证程序,然后使用代码中的validate()方法进行检查。这是一个例子:

<database ...>
  <table ...>
    <!-- the "required" attribute here only sets the DB property -->
    <column name="email" type="varchar" required="true" />
    ...
    <!-- Adds the unique index in the DB (but nothing in PHP code!) -->
    <unique>
      <unique-column name="email" />
    </Unique>
    ...
    <validator column="email">
      <!-- this validator rule makes the $obj->validate() method fail on null -->
      <rule name="required" message="The email is required!" />
      <!-- this validator rule makes the $obj->validate() method fail on empty string -->
      <rule name="minLength" value="1" message="The email cannot be blank!" />
      <!-- you could add a regular expression to only match email addresses here -->
      <rule name="match" value="/regular expression/" message="Please enter a valid email address!" />
      <!-- adds a validation that the field is unique before trying to update DB -->
      <rule name="unique" message="That email address is not unique!" />
    </validator>
  </table>
</database>

然后在您的preSave()代码中,您可以执行以下操作:

class User extends BaseUser {
  ...
  public function preSave(PropelPDO $con = null) {
    // does the object pass all validations?
    if (!$this->validate()) {
      $errors = array();
      // something failed, go through each failure and capture message:
      foreach ($this->getValidationFailures() as $failure) {
        $errors[] = $failure->getMessage();
      }
      // throwing an Exception will stop the save() from occurring
      throw new InvalidArgumentException(implode("||", $errors));
    }

    return true; // if you get here, go ahead and save
  }
}

在您的脚本中,您可以这样调用save()

...
$user = new User();
try {
  // try to save (could fail)
  $user->save();

} catch (InvalidArgumentException $e) {
  // we have errors, split the exception message to get each one separately
  $errorMessages = preg_split(/\|\|/, $e->getMessage());
  // handle the messages however you need to
}

详细了解Validators in the Propel documentation

答案 1 :(得分:0)

我认为如果未设置email列,您实际上想要停止插入/更新。实际上有一种正确的方法,使用hooks

请参阅以下代码以获取示例:

class User extends BaseUser
{
  // rest of code ...

  public function preSave(PropelPDO $con = null)
  {
    if ( empty($this->getEmail) ) {
        return false; 
    }
    return true;
  }
}

您还可以使用preInsert()preUpdate()来更好地控制何时验证数据。