使用 Datamapper ORM 保存表关系
我是对象模型映射的新手,刚刚阅读了 CodeIgniter DataMapper 的文档。我已经尝试过这些例子,并且给我留下了深刻的印象,一个人可以在很少的时间内取得很多成果。
但我似乎没有解决一个问题:
假设我有两个表:客户和地址。一位客户可以有多个地址,但我只能向一位客户发送地址。
现在,我有一个注册表,新客户必须输入存储在客户表中的个人数据和存储在地址表中的地址。
验证是在特定模型中完成的。我的问题是如何确保数据在将两个表保存到数据库之前都有效。
目前,客户可能为客户表输入了正确的数据,该数据已验证并保存到数据库,但地址数据未验证且未保存。
简而言之:如果所有表的数据都验证,我只想将任何表的数据保存到数据库,否则我想获取错误消息。
感谢您提前提供的任何帮助。
I am new to Object Model Mapping and just read the documentation of the CodeIgniter DataMapper. I have tried the examples and I am quite impressed in how little time one can achive a lot.
But I don't seem to get one problem solved:
Lets say I have two tables: customer and address. A customer can have many addresses but am address only one customer.
Now, I have a registration form where a new customer has to enter his personal data which is stored in the customer table and his address which is stored in the address table.
Validation is done in the specific models. My problem is how can I ensure that the data is valid for both tables prior to saving them to database.
At the moment it is possible that the customer enters the correct data for the customer table which validates and gets saved to db but the address data does not validate and is not saved.
In short: I only want to save the data of any table to db if the data for all tables validates else I want to get the error messages.
Thanks for any help in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一种方法是使用 transactions,第二种方法 - 验证地址和客户数据,如果两者都有效有效 - 存储。
First way is to use transactions, second - validate both address and customer data, and if both is valid - store.
文档中并不清楚,但您可以调用
validate()<调用
save()
之前的 /code> 方法:It's not clear from the documentation, but you can call the
validate()
method prior to callingsave()
:如果定义了验证规则,则不需要显式调用 validate(),调用 save() 时也会检查验证规则。
如果验证失败,save() 将返回 FALSE,之后您可以检查 $this->valid 以查看验证错误是否导致保存失败。
If you have validation rules defined, you don't need to explicitly call validate(), the validation rules will also be checked when you call save().
In case validation failed, save() will return FALSE, after which you can check $this->valid to see if a validation error caused the save to fail.