Kohana 3.1 ORM:空模型属性值保存为 0(零)而不是 NULL
我有两个模型:产品和产品_方法论。在我的产品编辑视图中,我有一个选择表单字段,可以选择多种方法中的一种或不选择任何方法(第一个选项为空)。在我的产品表中,我有一个 INT(10)
methodology_id
属性,该属性与从选择表单字段中选择的方法的 ID 一起保存。一切都工作正常,直到今天我不得不对系统进行调整,从现在起选择方法可以是可选的。因此,我更改了产品表的 methodology_id
字段以允许 NULL
值,并删除了模型上的 not_empty
验证规则。
问题是,现在当我选择空选项保存模型时,我得到的是 0
(零)值,而不是预期的 NULL
。
这方面有什么线索吗? 非常感谢,如果不清楚,请告诉我。
I have two models, Product and Product_Methodology. In my product edit view I have a select form field to select one of many methodologies or none (empty first option). In my products table I have a INT(10)
methodology_id
property that gets saved with the id of the methodology selected from the select form field. Everything worked OK until today that I had to make an adjustment to the system in which since now selecting a methodology can be optional. So I changed the methodology_id
field of the products table to allow NULL
value and removed the not_empty
validation rule on the model.
The problem is that now when I save the model selecting the empty option, instead of the expected NULL
, I get a 0
(zero) value.
Any clue on this?
Thanks a lot and let me know if it's not so clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您使用什么表单输入来选择方法?是
在这种情况下,我使用模型的
filters()
方法创建一个自定义过滤器,当它为empty()
时将值设置为 NULL(如 PHP 处理),如下所示:其中 Filter 是具有静态方法的辅助类。就像...:
希望这有帮助:)
What form input are you using for choosing the methodology? is it
<select>
?If so, the value of choosen option is probably set to 0 when no methodology is choosen, and send with other form data.
In such cases I make a custom filter withing model's
filters()
method, to set the value to NULL (as PHP treats it) when it'sempty()
, something like this:Where Filter is helper class with static methods. like...:
Hope this helps :)
即使提交的表单字段为空,它也是一个具有任何空值的字符串 - 而不是 NULL。当保存到 INT 字段时(至少在 mysql 中),它会被强制转换为 0。要保留空值,请执行以下操作:
Even if the submitted form field is blank it's a string with any empty value - not NULL. This gets cast as 0 when saved to an INT field (at least in mysql). To preserve a null value do something like this:
如果字段值为空字符串,则使用闭包返回 NULL 值的示例:
An example of using a closure to return a NULL value if the field value is an empty string:
您应该做的是将选择框中的无值的键设置为0。
您应该为该字段保留 not_empty 规则。然后,您应该为该字段制定一个规则,确保该值是 product_methodology 的合法值或零。
我扩展了 ORM 并具有以下两个函数:
如果您要使用这些函数,则 product 类中的规则将如下所示:
What you should do is set the key for the None value in your select box to 0.
You should leave the not_empty rule for the field. Then you should have a rule for the field that makes sure that the value is either a legitimate value for product_methodology or zero.
I extend ORM and have the following two functions:
If you were to use these functions, you're rules in the product class would look like: