dtotuki47568 2013-07-26 17:04
浏览 22
已采纳

如何在cakephp中处理相关模型添加操作?

I have two models, Dealer and DealerReview.
I want to create a form to add DealerReview from the DealersController, View action. What is the recommended way to achieve this in cakephp? Do i:

a) Create a form in DealersController view action but post the data to DealerReviewsController add action? OR

b) Post the add review data directly to DealersController, view action and add the record to the database from there?

  • 写回答

3条回答 默认 最新

  • douan0729 2013-07-26 17:20
    关注

    Really up to you...

    What you have to have in mind when choosing one way or the other is:

    for a)
    - the dealer that the review is related to will already be created? If not, how will you add the foreign key dealer_id to DealerReviews to relate both?

    for b)
    - this will nullify the trouble of not having a proper foreign key if the dealer is not created (of course, if you add the creation of dealer first)
    - you cannot reuse the add DealerReviews logic if you plan to add reviews from somewhere else.

    What I normally do is just post the data directly to the main controller (in this case Dealers). Saves me the trouble of having to check if the Dealer was correctly saved and validated before adding the Review.

    If there's a business logic to have in mind before saving the Review (like it can only be save between 2am and 3am (stupid example, I know)), then I add that validation in beforeSave.

    If it is a one-or-two-in-a-time business logic, I create a new function saveButOnlyInSomeCasesLogic($reviewArray) in the model and let that handle those cases, the controller just calls that function and waits for the result.

    In summary: choose the option that let you reuse code if you need to. If you will always have the foreign key available, do it in the Reviews controller, you may need to reuse the add action. If you will absolutely not reuse the add action or don't have the foreign key available when saving, to it in Dealers, keeping saving logic in the model if any.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 准备学习小程序搭建,谁能手把手的教我啊?
  • ¥15 关于#嵌入式硬件#的问题:树莓派第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没把原来的界面调回来
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e