本文介绍了CakePHP HABTM - 我不明白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前问过,但仍在黑暗中。





将重试:

我有两个表:商店经理

我想创建一个新表,managers_stores并使用它保存每个商店的管理器的完整列表。

我理解每个 save()操作,将提供完整的记录数据(如我打算做的)将导致表行删除,只有新的记录将被保留。

这是一个对我的需要的一个UNDESIRED行为。那么,我应该如何管理我的应用程序的HABTM信息,以及删除我保存的数据背后的想法?



感谢

c> save()不会删除任何内容,只保存 saveAll()将截断您要保存的特定模型的 managers_stores 条目,如果 unique 关系的值 true 。这在手册中未完全清楚:

每当你 save()一个单独的记录,只有那个单独的记录被触摸。

当你 saveAll 记录与存储记录同时存在的 code> managers_stores 链接将被重置,并且只有您保存的记录中的商店将与经理关联。例如。 (以伪代码):




  • 经理HABTM商店1,2和3

  • Manager-> saveAll(array('Manager'=> ...,'Store'=> array(4,5,6)))

  • 经理现在HABTM商店4,5和6;现有的关联已被覆盖



因此,要么设置 unique 关联到 false ,如果您不喜欢此行为,或手动管理HABTM记录。说实话,对于任何半途复杂的应用程序,依赖Cake的自动处理HABTM关系可能会变得相当脆弱和难以调试,所以我自己总是管理HABTM记录。

  $ this-> Manager-> save(...); 
$ this-> Manager-> ManagersStore-> save(array('manager_id'=> $ this-> Manager-> id,
'store_id'=> 42) );


Asked before but still in the dark.

cakePHP HABTM, am i getting it all wrong?

Will try again:
I have two tables: stores and managers
I want to create a new table, managers_stores and use it to keep a complete list of mangers for each store.
I understood that each save() action that will provide the full record data (as I intend to do) will result in the deletion of the table rows and only the new record will be kept..
This is an UNDESIRED behavior for my needs. So, how should I manage the HABTM info of my application and what's the idea behind deleting data that I saved?!

thanks

解决方案

save() will not delete anything, only saving with saveAll() will truncate the managers_stores entries for the particular model you're saving, if the unique value of the relationship is true. This is not made entirely clear in the manual:

Whenever you save() an individual record, only that individual record will be touched.
When you saveAll() a, say, Manager record with associated Store records in the same go, the managers_stores links will be reset and only the Stores that were in the record you saved will be associated with the Manager. E.g. (in pseudo code):

  • Manager HABTM stores 1, 2 and 3
  • Manager->saveAll(array('Manager' => ..., 'Store' => array(4, 5, 6)))
  • Manager now HABTM stores 4, 5 and 6; the existing associations were overwritten

So, either set the unique value in the association to false if you don't like this behavior, or manage the HABTM records manually. To be quite honest, for any halfway complex application, relying on Cake's automagic handling of HABTM relationships can get quite fragile and hard to debug, so I always manage HABTM records myself.

$this->Manager->save(...);
$this->Manager->ManagersStore->save(array('manager_id' => $this->Manager->id,
                                          'store_id'   => 42));

这篇关于CakePHP HABTM - 我不明白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:20