2

我有两个模型:绘图有很多面板,面板属于绘图。每次保存面板时,我都想检查它是否是要添加到绘图中的第三个面板。如果是,我想将三个面板合并为一个新的 png 文件,并将 png 的文件名和路径保存到绘图表。

class Drawing extends AppModel {
  public $name = 'Drawing';
  public $hasMany = array(
    'Panel' => array(
        'className' => 'Panel',
        'dependent' => true,
        'fields' => array('id', 'filepath', 'filename', 'placement')
        )
  );
}

class Panel extends AppModel {
  public $name = 'Panel';
  public $belongsTo = array(
    'Drawing'=>array(
        'className'=>'Drawing',
        'foreignKey'=>'drawing_id',
        'counterCache' => true
        )
    );
}

由于我在 Panel 模型中将 counterCache 设置为 true,因此我在绘图表中使用 panel_count 跟踪面板——并且我可以检查何时有 3 个面板。我认为最好的方法是使用 afterSave() 回调。这样,我可以检查现在是否有三个面板,如果有,我可以更新我想要的任何内容。(一旦有三个面板,我的控制器会阻止用户添加新面板)。但是,我认为下面的代码不起作用——它会阻止我的应用程序的其他部分运行,如果我删除 afterSave() 函数,一切都会再次运行。如何从我的绘图模型中检查 panel_count?有一个更好的方法吗?

// Inside of the Drawing model... 
public function afterSave($created){
  if ($this->data[panel_count] == 3){
    // create a new image by merging the three panel images together
    // add the filename and path of the new image to the database
  }
}
4

1 回答 1

0

创建一个新的模型方法来执行该功能并使用控制器中的该方法进行保存。原因是 Drawing.panel_count 属性的更改(您必须更新绘图记录,这会创建一个 afterSave 循环)。

我通常避免任何数据修改的回调(尤其是在同一模型中),因为它们每次都运行,有时我只是想保存而不需要额外的修改。将一段代码从方法移动到 afterSave 回调也比其他方式更容易。

于 2013-01-27T10:03:04.050 回答