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条)

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效