3

未设置列时,如何防止 Propel ORM 插入空字符串?

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

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

4

2 回答 2

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
}

在 Propel 文档中阅读有关验证器的更多信息。

于 2013-04-25T14:35:25.963 回答
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()来更好地控制何时验证数据。

于 2013-04-25T11:26:24.347 回答