Не допускайте, чтобы 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(); $user = new User(); $user->save(); , Я попытался установить SQL_MODE но это не помогает.

Related of "Не допускайте, чтобы Propel вставлял пустые строки"

Правильный способ сделать это – проверить валидатор в схеме, а затем проверить с помощью метода 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 .

Я думаю, вы действительно хотите остановить вставку / обновление, если столбец email не установлен. Фактически есть правильный способ сделать это, и это с помощью перехватчиков .

Для примера см. Следующий код:

 class User extends BaseUser { // rest of code ... public function preSave(PropelPDO $con = null) { if ( empty($this->getEmail) ) { return false; } return true; } } 

Вы также можете использовать preInsert() или preUpdate() для получения дополнительных preUpdate() о том, когда проверять данные.