我有一个带有性别枚举字段的用户表,其中包含男/女选项。如果我创建一个用户,如果我尝试将性别设置为例如“变性人”,则会抛出异常。
是否可以允许将变性人设置为“变性人”'如果我调用validate()函数,只会得到验证错误?所以它与其他领域一起验证了吗?
Schema.xml的:
<table name="user" idMethod="native" namespace="Models" package="Models">
<column name="id" type="INTEGER" sqlType="INTEGER(11) UNSIGNED" primaryKey="true" autoIncrement="true" required="true"/>
<column name="first_name" type="VARCHAR" required="true"/>
<column name="mail" type="VARCHAR" required="true"/>
<column name="gender" type="ENUM" valueSet="male, female"/>
<behavior name="validate">
<parameter name="rule1" value="{column: first_name, validator: NotNull}" />
<parameter name="rule2" value="{column: mail, validator: NotNull}" />
<parameter name="rule3" value="{column: gender, validator: NotNull}" />
<parameter name="rule4" value="{column: gender, validator: ValidEnum}" />
</behavior>
</table>
PHP代码:
$user = new User();
$user->setFirstName('John');
$user->setMail('johndoe@gmail.com');
$user->setGender('transgender'); // currently throws an exception
if ($user->validate()) {
$user->save();
} else {
// handle exception
}
答案 0 :(得分:0)
由于您可能会遇到异常,因此可以将其包装在try-catch块中。
try {
$user = new User();
$user->setFirstName('John');
$user->setMail('johndoe@gmail.com');
$user->setGender('transgender'); // currently throws an exception
$user->save();
} catch (PropelException $e) {
echo $e->getMessage(); // Value "transgender" is not accepted in this enumerated column
}